Monday, October 27, 2008

Working with Drives, Directories and Files in ASP.NET

Working with Drives, Directories and Files in ASP.NET
This article explain and list sample code that you need to work and manipulate files, directories in ASP.NET

Introduction

Many times in your ASP.NET applications, you need to interact with the local file system, directory structures, reading and writing to files. or performing many other tasks. The System.IO namespace in the .NET framework makes working with file system and directories very easy. However there are things you need to keep in mind that is security. When you reading, or writing a file or folders in Web application, you are actually executing on behalf of the users that being assigned to your web application and mostly it is under ASP.NET user or Network Service user. You need to make sure that the user itself has write or read access for the particular file or directory you are working on.

In this article, I will list down few important classes in .NET that you need to know in order to manipulate files and folders in ASP.NET application.
The DriveInfo Class

A new addition to the .NET Framework 2.0 in System.IO namespace is DriveInfo Class. This class supplements the GetLogicalDrives() method of the Directory class included in prior versions of the .NET framework. It provides you with the extended information on any drive registered with the server's local system. You can get information such as name,type,size, and status of each drive.

protected void Page_Load(object sender, EventArgs e)
{
System.IO.DriveInfo drive = new System.IO.DriveInfo(@"C:\");
Response.Write ("Drive Name " + drive.Name + "
");
Response.Write ("Drive Type " + drive.DriveType.ToString() + "
");
Response.Write ("Available Free Space " + drive.AvailableFreeSpace.ToString() + "<BR>");
Response.Write ("Drive Format " + drive.DriveFormat + "
");
Response.Write ("Total Free Space " + drive.TotalFreeSpace.ToString() + "<BR>");
Response.Write ("Total Size " + drive.TotalSize.ToString() + "
");
Response.Write ("Volume Label " + drive.Total.VolumeLabel + "
");

}

Output :
Drive Name : C:\
Drive Type : Fixed
Available Free Space : 731546886
Drive Format : NTFS
Total Free Space : 723564656
Total Size : 855456232

The Directory and DirectoryInfo Classes

The next classes that I will list down the sample code is Directory and DirectoryInfo class. From the class name, you can actually know that these classes will be dealing with directories.
The Directory Class exposes static method you can use to create, move and delete directories.

In the sample code below, I will use the TreeView controls to display the directories just like Windows Explorer TreeView.

protected void Page_Load(object sender,EventArgs e)
{
foreach(System.IO.DriveInfo drive in System.IO.DriveInfo.GetDrives())
{
TreeNode oNode = new TreeNode();
node.Value = drive.Name;
if(drive.IsReady)
{
node.Text = drive.Name + "- (free Space :" + drive.AvailableFreeSpace + ")";
LoadDirectories(node,drive.Name);
}
else
{
node.Text = drive.Name + " - (Not ready)");
}
this.TreeView1.Nodes.Add(node);
}
this.TreeView1.CollapseAll();
}

private void LoadDirectories(TreeNode parent, string path)
{
System.IO.DirectoryInfo directory = new System.IO.DirectoryInfo(path);
try
{
foreach(System.IO.DirectoryInfo d in directory.GetDirectories())
{
TreeNode node = new TreeNode(d.Name,d.FullName);
parent.ChildNodes.Add(node);
LoadDirectories(node,d.FullName);
}
}
catch(System.UnauthorizedAccessException e)
{
parent.Text += "(Access Denied)";
}
catch(System.IO.IOException e)
{
parent.Text += "(Unknown Error : " + e.Message +")";
}
}

//Create a New Directory
DirectoryInfo objDirectoryInfo = Directory.CreateDirectory("C:\\Test");

//Create a Directory Within an Existing Directory
DirectoryInfo childDir = objDirectoryInfo.CreateSubdirectory("Dir");

//Get Parent of a Directory
DirectoryInfo parentDir = childDir.Parent;

//Get All Files of a Directory
FileInfo[] fiList = parentDir.GetFiles();

//Get Files of a Directory Starting With Text "abc"
FileInfo[] fiFilteredList = parentDir.GetFiles("abc*");

//Delete an Empty Directory
childDir.Delete();

// Delete a Non Empty Directory
objDirectoryInfo.Delete();



File and FileInfo

File and FileInfo classes basically deals with files. You can get all the file properties inside the File and FileInfo classes. Code example below.

foreach(System.IO.FileInfo file in dir.GetFiles("*.*"))
{
Response.Write(file.Name + "<BR>");
Response.Write(file.LastWriteTime.ToString() + "<BR>");
Response.Write(file.Attributes.ToString() + "<BR>");
}

string sPath = @"C:\Data\Database\MyDocument.xml";
Response.Write ("Directory Name = " + Path.GetDirectoryName(sPath));
Response.Write ("File Extension = " + Path.GetExtension(sPath));
Response.Write ("File Name = " + Path.GetFileName(sPath));
Response.Write ("File Name without extension = " + Path.GetFileNameWithoutExtension(sPath));
Response.Write ("Full Path = " + Path.GetFullPath(sPath));


Working with Paths
From the code above, you can see that working with files and directories has been pretty easy with .NET Framework. Microsoft also has introduce one class called System.IO.Path that allow you to deal with paths. You know that previously in old ASP, or in VB language prior to .NET , it has been extremely difficult dealing with paths. Many lines of code have been written by the developers to deal with concatenating partial paths together, making sure files have extensions, evaluating those extensions, stripping filenames off of paths, and even more.

private void WriteFile()
{
string FilePath = Server.MapPath("Data.txt");
StreamWriter writer = new StreamWriter(FilePath);
writer.Write("Testing 1");
writer.WriteLine();
writer.Write("Testing 2");
writer.WriteLine();
writer.Write("Testing 3");
writer.Close();
}

The output of the code above will be like this :
DirectoryName = C:\Data\Database
File Extension = .xml
File Name = MyDocument.xml
FileName without extension = MyDocument

I think everybody should agree with me that playing and manipulating path is now very easy, and we don't have to write our own logic, manipulating strings, just to strip out the filename or the extension.
Everything has been provided inside the Path class.
Reading and Writing Files

From the article above, you have learned how to manage and manipulate files on the local system. Now we are trying to discuss the I/O operations in .NET Framework. The .NET Framework makes performing I/O operations easy because it uses a common model of reading or writing I/O data. The model is based on two basic concepts, Stream Classes and Reader/Writer classes.
StreamReader and StreamWriter

Writing files on your website can be accomplished by using the help of StreamReader and StreamWriter Class inside the System.IO namespace.

Code sample on how to write file on your webserver. Before you proceed with the code below,make sure that your ASP.NET user or Network Service User has write permission on the particular folder or files that you want to write.

Writing File on Web Server in ASP.NET (This will Delete Existing file and recreate new file)

private void AppendFile()
{
string FilePath = Server.MapPath("Data.txt",true);
StreamWriter writer = new StreamWriter(FilePath);
writer.Write("Testing 4");
writer.WriteLine();
writer.Write("Testing 5");
writer.WriteLine();
writer.Write("Testing 6");
writer.Close();
}

Append Existing Files on Web Server (Append existing content)

private void AppendFile()
{
string FilePath = Server.MapPath("Data.txt",true);
StreamWriter writer = new StreamWriter(FilePath);
writer.Write("Testing 4");
writer.WriteLine();
writer.Write("Testing 5");
writer.WriteLine();
writer.Write("Testing 6");
writer.Close();
}

No comments: