How To Read File Information With ASP.NET?
If you try to create file manager in ASP.NET or simply you want to know some specific attribute of some file, you can use FileInfo class to get all needed file information. Bellow is simple code example about how to use FileInfo class. You can copy/paste this code to see how it works. Just replace "products.xml" with needed file.
[ C# ]
// To
read file information, we need System.IO namespace
using
System.IO;
public
partial class
DefaultCS : System.Web.UI.Page
{
protected void
Page_Load(object sender, System.EventArgs
e)
{
string FilePath = Server.MapPath("products.xml");
FileInfo MyFileInfo =
new FileInfo(FilePath);
string FileInformation =
"<strong>File information:</strong><br />";
// Check if file exists
if(MyFileInfo.Exists)
{
// File exists, take data about it
FileInformation = "File Name: " +
MyFileInfo.Name + "<br />";
FileInformation += "Directory: " +
MyFileInfo.DirectoryName + "<br />";
FileInformation += "Full path: " +
MyFileInfo.FullName + "<br />";
FileInformation += "Time Created: " +
MyFileInfo.CreationTime + "<br />";
FileInformation += "Time Modified: " +
MyFileInfo.LastWriteTime + "<br />";
FileInformation += "Last Access Time: " +
MyFileInfo.LastAccessTime + "<br />";
// Gets file size in bytes
FileInformation += "File Size: " +
MyFileInfo.Length + "<br />";
// Gets extension part of file name
FileInformation += "File Extension: " +
MyFileInfo.Extension;
}
else
{
// File not exists, inform a user about it
FileInformation = "There is no file on <strong>"
+ FilePath + "</strong>.";
}
Response.Write(FileInformation);
}
}
[ VB.NET ]
' To
read file information, we need System.IO namespace
Imports
System.IO
Partial
Class _Default
Inherits System.Web.UI.Page
Protected Sub
Page_Load(ByVal sender
As Object, ByVal
e As System.EventArgs)
Handles Me.Load
Dim FilePath As
String = Server.MapPath("products.xml")
Dim MyFileInfo As
FileInfo = New FileInfo(FilePath)
Dim FileInformation As
String =
"<strong>File information:</strong><br />"
' Check if file exists
If (MyFileInfo.Exists)
Then
'
File exists, take data about it
FileInformation = "File Name: " &
MyFileInfo.Name & "<br />"
FileInformation &= "Directory: " &
MyFileInfo.DirectoryName & "<br />"
FileInformation &= "Full path: " &
MyFileInfo.FullName & "<br />"
FileInformation &= "Time Created: " &
MyFileInfo.CreationTime & "<br />"
FileInformation &= "Time Modified: " &
MyFileInfo.LastWriteTime & "<br />"
FileInformation &= "Last Access Time: " &
MyFileInfo.LastAccessTime & "<br />"
' Gets file size in bytes
FileInformation &= "File Size: " &
MyFileInfo.Length & "<br />"
' Gets extension part of file name
FileInformation &= "File Extension: " &
MyFileInfo.Extension
Else
' File not exists, inform a user about it
FileInformation = "There is no file on <strong>"
& FilePath & "</strong>."
End If
Response.Write(FileInformation)
End Sub
End
Class
Related articles:
1. XML Automatic Documentation Tags