Common operation with Files and Folders in ASP.NET

SheoNarayan
Posted by in ASP.NET category on for Intermediate level | Views : 21584 red flag
Rating: 5 out of 5  
 1 vote(s)

In this article, I shall show how to do common operations like Copy, Move, Delete, Create, Rename and Search files and folders in ASP.NET.


 Download source code for Common operation with Files and Folders in ASP.NET

Introduction

Very frequently while working on different applications these day, we need to do some common operations like creating, copying, moving or searching files and folders. In this article, I am going to show how to do these common operations on Files and Folders. In order to show them, I have created a web page that looks like below. I have attached the source code for this article at the top so that you can play with them and understand it very easily. Please feel free to download and use it.

The code for above UI is below.

<div>

<h4>Working with Files and Folders in ASP.NET</h4>

<table cellpadding="4" cellspacing="0" style="border:1px solid #c0c0c0;border-collapse:collapse;" border="1">

<tr>

<th><u>Drives</u></th>

<th><u>Folders</u></th>

<th><u>Files</u></th>

<th><u>Action</u></th>

</tr>

 

<tr valign="top">

<td><asp:Label ID="lblDrives" ForeColor="Red" runat="Server" /></td>

<td><asp:Label ID="lblFolder" ForeColor="Brown" runat="Server" /></td>

<td><asp:Label ID="lblFiles" runat="Server" /></td>

<td>

Name: <asp:TextBox ID="txtFile" runat="Server" /><br />

Folder Name: <asp:TextBox ID="txtFolder" runat="Server" />

<p>

<asp:RadioButtonList ForeColor="blue" ID="radioAction" runat="Server" RepeatDirection="Vertical" RepeatLayout="Flow">

<asp:ListItem Text="Copy File" Value="Copy" Selected="True" />

<asp:ListItem Text="Move File" Value="Move" />

<asp:ListItem Text="Delete File" Value="Delete" />

<asp:ListItem Text="Create Folder" Value="Create Folder" />

<asp:ListItem Text="Delete Folder" Value="Delete Folder" />

<asp:ListItem Text="Rename File" Value="Rename File" />

<asp:ListItem Text="Rename Folder" Value="Rename Folder" />

<asp:ListItem Text="Search File" Value="Search File" />

<asp:ListItem Text="Search Directory" Value="Search Directory" />

</asp:RadioButtonList></p>

<asp:Label ID="lblSearch" runat="server" EnableViewState="False" />

<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="DoAction" />

</td>

</tr>

</table>

<asp:Label ID="lblMessage" runat="Server" ForeColor="Red"></asp:Label>

</div>

If you want to create a new text file or append the contents into it, you can read http://www.dotnetfunda.com/articles/article462-different-ways-of-reading-and-writing-text-file-data-in-net.aspx.

Let's see how to do common operations using C# code, you can easily convert these codes into VB.NET using http://converter.telerik.com/ 

Following code are the part of my method named ListFilesFolders() in the attachment that has following code at the top of the method that has been used to work with different objects (like DirectoryInfo, FileInfo) used in the method, these objects are part of System.IO namespace.

Code Snippet - 1

StringBuilder strB = new StringBuilder();

string folderName = @"E:\Learn\Csharp\";

DirectoryInfo directory = new DirectoryInfo(folderName);

List all drives

To list all the drives of the computer, you can use below code.

Code Snippet - 2

// list drives

foreach (DriveInfo drive in DriveInfo.GetDrives())

{

strB.Append(drive.Name + "<br />");

}

lblDrives.Text = strB.ToString();

 

// to list all the drivers, below code snippet can also be used

/* string[] d = Environment.GetLogicalDrives();

foreach (string s in d)

{

Response.Write(s + "<br />");

} */

In this, I have used DriverInfo.GetDrives() method that will give me the array of DriverInfo object that I used to loop through and write the name of the drives. Almost same can be achieved using Environment.GetLogicalDrives() method, that gives us array of string that contains the name of the drives. But notice that DriverInfo object will give more options to know about that drive like size, format etc. so if you need to know more than just the name of the drives, you can use DriverInfo.GetDrives() method.

Get solutions of .NET problems with video explanations, .pdf and source code in .NET How to's.

List all folders

To list all the sub folders of the directory, I have used following code snippets

Code Snippet - 3

// list folders

foreach (DirectoryInfo dir in directory.GetDirectories())

{

strB.Append(dir.Name + "<br />");

}

lblFolder.Text = strB.ToString();

Here, I have used directory object from Code Snippet - 1 and executed its GetDirectories() method that gives us an array of DirectoryInfo object that has been used to list out the name of directoreis under specified folder (refer folderName variable in Code Snippet - 1). There are many properties and methods exists in the DirectoryInfo object that can be used to get the full name of the directory (including path), whether it exists or not, created date time, last accessed time etc.

List all Files

To list all files, I have used following code snippets

// list files now

foreach (FileInfo file in directory.GetFiles())

{

strB.Append(file.Name + "<br />");

}

lblFiles.Text = strB.ToString();

Here, I have used GetFiles() method of the directory object (refer to Code Snippet - 1) that gives us an array of FileInfo object that has been used to list the name of the folder under that directory. There are many properties or methods exists in the File object that can be used to get the extension of the file, whether it exists or not, created date time, last accessed time etc.

Lets perform some actions now.

Now as displayed in the picture, I am performing some common actions on the files and folders. Lets see the method that fires when the submit button is clicked.

/// <summary>

/// Do action now

/// </summary>

/// <param name="sender"></param>

/// <param name="e"></param>

protected void DoAction(object sender, EventArgs e)

{

string command = radioAction.SelectedValue;

string folder = folderName + txtFolder.Text;

string file = txtFile.Text;

string source = string.Empty;

string destination = string.Empty;

StringBuilder strB = new StringBuilder();

try

{

switch (command)

{

case "Copy":

source = folderName + file;

destination = folder + "\\" + file;

File.Copy(source, destination);

break;

case "Move":

source = folderName + file;

destination = folder + "\\" + file;

File.Move(source, destination);

break;

case "Delete":

destination = folder + "\\" + file;

File.Delete(destination);

break;

case "Create Folder":

destination = folder + "\\" + file;

Directory.CreateDirectory(destination);

break;

case "Delete Folder":

destination = folder + "\\" + file;

Directory.Delete(destination);

break;

case "Rename File": // there is no Rename method so use Move

source = folderName + file;

destination = folderName + txtFolder.Text;

File.Move(source, destination);

break;

case "Rename Folder": // there is no Rename method so use Move

source = folderName + file;

destination = folderName + txtFolder.Text;

Directory.Move(source, destination);

break;

case "Search File":

strB.Append("<b>Searching Files : " + txtFile.Text + "</b><br />");

DirectoryInfo directory = new DirectoryInfo(folderName);

foreach (FileInfo f in directory.GetFiles(txtFile.Text, SearchOption.TopDirectoryOnly))

{

strB.Append(f.FullName + "<br />");

}

lblSearch.Text = strB.ToString();

break;

case "Search Directory":

strB.Append("<b>Searching Directories: " + txtFile.Text + "</b><br />");

DirectoryInfo dir = new DirectoryInfo(folderName);

foreach (DirectoryInfo f in dir.GetDirectories(txtFile.Text, SearchOption.AllDirectories))

{

strB.Append(dir.FullName + "<br />");

}

lblSearch.Text = strB.ToString();

break;

}

lblMessage.Text = "File Action <b>" + command + "</b> done successfully!";

ListFilesFolders(); // refresh the list

}

catch (Exception ee)

{

lblMessage.Text = ee.Message;

}

}

Copy File

To copy a file from one folder to another folder, simply use File.Copy method and specify the source file name and desitnation file name, please note that the both file names must contain the name of the file along with full path.

Move File

To move a file from one folder to another, use File.Move method and pass source and desitnation file name, again the source and destination file names must contain the full path of the file to move and the destination file name along with full path.

Delete File

To delete a file, use File.Delete method and pass the name of the file along with path as parameter and the file will be deleted permanently.

Create Folder

To create a folder, use Directory.CreateDirectory method and pass the new directory name as parameter, again this should contain the complete path of the directory to be created.

Delete Folder

To delete a folder, use Directory.Delete method and pass the directory to be deleted as parameter, please note that unless the directory is empty (there must not be any file in that directory) you will not be able to delete that. You need to pass the complete path of the directory as parameter to delete it.

Rename File

There is no Rename method as such with the System.IO.File class, so the trick is to use File.Move method and pass source and destination folder as the same but specify the name of the file differently that will work as Rename.

Rename Folder

Same as Renaming file, we do not have any inbuilt method as RenameMethod so we can use Directory.Move and pass source and destination. Here destination should contain the name of the directory you want to rename with the old directory.

Search File

In order to search a file name for a particular search pattern, you can use GetFiles() method of DirectoryInfo object and pass two parameter, the search pattern to be searched in the name of the file and Search option to search only current directory or all the sub directories under current folder. Please note that you have freedom to use the wild card characters in the file name to search to filter or broaden your search result.

Search Directory

Same as Search file, we can use GetDirectories method of DirectoryInfo object and pass two parameter, the directory to search and parent folder to search in. Same as File search, you can use wild card characters to filter or broaden your serch result in the directory to search.


Conclusion

Using System.IO namespace, we can do all common operation on files and folders. Hope you liked this article, please subscribe for the subsequent article alert directly in your email box.

Thanks for reading, wish you a happy coding !

Page copy protected against web site content infringement by Copyscape

About the Author

SheoNarayan
Full Name: Sheo Narayan
Member Level: HonoraryPlatinum
Member Status: Administrator
Member Since: 7/8/2008 6:32:14 PM
Country: India
Regards, Sheo Narayan http://www.dotnetfunda.com

Ex-Microsoft MVP, Author, Writer, Mentor & architecting applications since year 2001. Connect me on http://www.facebook.com/sheo.narayan | https://twitter.com/sheonarayan | http://www.linkedin.com/in/sheonarayan

Login to vote for this post.

Comments or Responses

Posted by: Poster on: 1/19/2010
Very useful and consolidated articles on working files and folders.

Thank you very much for sharing this info.

Regards
Posted by: Raja on: 2/12/2010
Great article sir.

Thanks
Posted by: Virendradugar on: 3/8/2010
Great job done.

Thanks,
Virendra Dugar

Login to post response

Comment using Facebook(Author doesn't get notification)