AspAlliance.com LogoASPAlliance: Articles, reviews, and samples for .NET Developers
URL:
http://aspalliance.com/articleViewer.aspx?aId=920&pId=-1
Working with Files and Directories using ASP.NET
page
by SANJIT SIL
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 55274/ 63

Introduction

In our real life applications it is required to read, write, or manipulate files and directories.  The .NET Framework provides a set of classes in the System.IO namespace to allow synchronous and asynchronous reading from and writing to data streams and files.  Before working with files and directories it is essential to make sure that security permissions are set properly on folders and files where you want to write.  The .NET Framework runs all ASP.NET processes under the local ASPNET account.  This account needs to have write permissions to all the folders and files that are being used to write data.  To set permissions of that folder the steps to be followed are: right-click the folder, go to properties, security tab, and then make sure the local ASPNET account has read and write permissions on that folder.  If they do not, add local ASPNET account to the list and give it read and write permissions and then click ok.  In this article I have tried to discuss most of the methods available in the Directory, DirectoryInfo, File and FileInfo classes.  The sample code snippets in this article have been written in C#.

Managing Directories

There are two classes to manage directories, Directory and DirectoryInfo.

Directory

The Directory class is responsible for creating, moving and enumerating directories and subdirectories.  All of its methods are static and require a security check for each call.  The security check verifies the permission of the current user to perform the specified operation.  The methods of Directory class have been explained in the sections that follow.

CreateDirectory Method

CreateDirectory Method creates a directory if one does not exist.

Listing 1

Directory.CreateDirectory(@"E:\TestDirectory");

Delete Method

Delete method deletes a directory.

Listing 2

Directory.Delete(@"E:\TestDirectory");

Exists Method

Exists Method determines the existence of a given directory.

Listing 3

Directory.CreateDirectory(@"E:\TestDirectory");
if(Directory.Exists(@"E:\TestDirectory"))
Response.Write("Directory Exist");
else
Response.Write("Directory does not exist");

GetCreationTime Method

GetCreationTime Method displays the date and time of creation of a given directory.

Listing 4

Response.Write(Directory.GetCreationTime(@"E:\TestDirectory"));

GetCurrentDirectory Method

GetCurrentDirectory Method returns the path of current working directory of the application.

Listing 5

String cd=Directory.GetCurrentDirectory();

GetDirectories Method

GetDirectories Method returns a string array filled with the fully qualified names of each contained directory of a given directory.

Listing 6

string[] abc=Directory.GetDirectories(Server.MapPath("Repository"));
foreachstring a in abc)                                   
{
Response.Write(a);
Response.Write("<BR>");
}

The GetDirectories Method is overloaded.  We can pass the search pattern as a string in the form of a second optional parameter, which will return a string array filled with the fully qualified names of each contained directory that matches the search pattern of a given directory.

Listing 7

string[] abc=Directory.GetDirectories(Server.MapPath("Repository"),"b*");
foreachstring a in abc)                           
{
Response.Write(a);
Response.Write("<BR>");
}

In the above code listing all directories will be displayed starting with the letter b.

GetDirectoryRoot Method

GetDirectoryRoot Method returns root information after taking a path as an argument.

Listing 8

cd=Directory.GetDirectoryRoot(@"E:\TestDirectoryFile");

GetFiles Method

GetFiles Method returns a string array filled with the fully qualified names of each contained file of a given directory.

Listing 9

string[] abc=Directory.GetFiles(Server.MapPath("Repository"));
foreachstring a in abc)                                                                      
{
Response.Write(a);
Response.Write("<BR>");
}

The GetFiles Method is overloaded.  We can pass the search pattern as a string in the form of a second optional parameter, which will return a string array filled with the fully qualified names of each contained file that matches the search pattern of a given directory.

Listing 10

string[] abc=Directory.GetFiles(Server.MapPath("Repository"),"*.aspx");
foreachstring a in abc)                                            
{
Response.Write(a);
Response.Write("<BR>");
}

In the above code listing all files having extension aspx will be displayed.

GetFileSystemEntries Method

GetFileSystemEntries Method returns a string array filled with the fully qualified names of each contained directory and file of a given directory.

Listing 11

string[] abc=Directory.GetFileSystemEntries(Server.MapPath("Repository"));
foreachstring a in abc)                                                                      
{
Response.Write(a);
Response.Write("<BR>");
}

The GetFileSystemEntries Method is overloaded.  We can pass the search pattern as a string in the form of a second optional parameter, which will return a string array filled with the fully qualified names of each contained directory and file that matches the search pattern of a given directory.

Listing 12

string[] abc=Directory.GetFileSystemEntries(Server.MapPath("Repository"), "b*");
foreachstring a in abc)                                                  
{
Response.Write(a);
Response.Write("<BR>");
}

In the above code listing all files and directories will be displayed starting with letter b.

GetLastAcessTime Method

GetLastAccessTime returns the last access date and time of the file or directory as specified in the path.

Listing 13

string cd=Directory.GetLastAccessTime(@"E:\TestDirectoryFile").ToString();

GetLastWriteTime Method

GetLastWriteTime returns the last modified date and time of the file or directory as specified in the path.

Listing 14

string cd=Directory.GetLastWriteTime(@"E:\TestDirectoryFile").ToString();

GetLogicalDrives Method

GetLogicalDrives Method returns a string array that contains a list of the available drives.

Listing 15

string[] abc=Directory.GetLogicalDrives();
foreachstring a in abc)
                                                                      
{
Response.Write(a);
Response.Write("<BR>");
}

GetParent Method

GetParent Method returns the parent directory of the specified path.

Listing 16

string cd=Directory.GetParent("E:\\TestDirectoryFile").ToString();

SetCreationTime Method

SetCreationTime Method sets the date and time of the file or directory as specified in the path.

Listing 17

Directory.SetCreationTime("E:\\TestDirectoryFile1",System.DateTime.Now);

SetCurrentDirectory Method

SetCurrentDirectory Method sets the application’s current working directory to the directory as specified in the path.

Listing 18

Directory.SetCurrentDirectory(@"E:\TestDirectoryFile");

SetLastAccessTime Method

SetLastAccessTime Method sets the last access date and time of the file or directory as specified in the path.

Listing 19

Directory.SetLastAccessTime("E:\\TestDirectoryFile",System.DateTime.Now);

SetLastWriteTime Method

SetLastWriteTime Method sets the last written date and time of the directory as specified in the path.

Listing 20

Directory.SetLastWriteTime(("E:\\TestDirectoryFile1",System.DateTime.Now); 

Move Method

Move Method moves a file or a directory and its contents to a new location.

Listing 21

Directory.Move("E:\\TestDirectoryFile1","E:\\TestDirectoryFile2");

DirectoryInfo

The DirectoryInfo class is similar to the Directory class, but contains only static methods.  A security check is performed only when the instance is created.  The methods of DirectoryInfo class have been explained in the sections that follow.

Create Method

Create Method creates a directory.

Listing 22

DirectoryInfo di=new DirectoryInfo(@"E:\TestDirectoryFile");
di.Create();  

CreateSubdirectory Method

CreateSubDirectory Method creates a subdirectory.

Listing 23

di.CreateSubdirectory(“TestSubDirectory”);

Delete Method

Delete Method deletes the directory.  This method is overloaded.

Listing 24

di.Delete();  // use when directory is empty;

di.Delete(true); // use to delete all files and directories in the directory.

GetDirectories Method

GetDirectories Method returns the subdirectories of the given directory.

Listing 25

DirectoryInfo df=new DirectoryInfo(Server.MapPath("Storage"));                      
DirectoryInfo[] abc=df.GetDirectories();
for(int i=0;i<abc.Length;i++)                                 
{
Response.Write(abc[i]);
Response.Write("<BR>");
}

GetDirectories Method is overloaded.  We can pass the search pattern as a string in the form of an optional parameter, which will return a directory list containing the name of each directory that matches the search pattern.

Listing 26

DirectoryInfo df=new DirectoryInfo(Server.MapPath("Storage"));
DirectoryInfo[] abc=df.GetDirectories("D*");
for(int i=0;i<abc.Length;i++)                                 
{
Response.Write(abc[i]);
Response.Write("<BR>");
}

In the above code listing all directories will be displayed starting with the letter D.

GetFiles Method

The GetFiles Method returns a file list from the current directory.

Listing 27

DirectoryInfo df=new DirectoryInfo(Server.MapPath("Storage"));
FileInfo[] abc=df.GetFiles();
for(int i=0;i<abc.Length;i++)
{
Response.Write(abc[i]);
Response.Write("<BR>");
}

The GetFiles Method is overloaded.  We can pass the search pattern as a string in form of an optional parameter, which will return a file list containing the name of each file that matches the search pattern of a given directory.

Listing 28

DirectoryInfo df=new DirectoryInfo(Server.MapPath("Storage"));
FileInfo[] abc=df.GetFiles("x*");
for(int i=0;i<abc.Length;i++)
{
Response.Write(abc[i]);
Response.Write("<BR>");
}

In the above code listing all files will be displayed starting with the letter x.

GetFileSystemInfos Method

 GetFileSystemInfos Method gets a collection of all the files and directories inside a folder.

Listing 29

DirectoryInfo di=new DirectoryInfo(@"E:\TestDirectoryFile");
FileSystemInfo[] abc=di.GetFileSystemInfos();
for(int i=0;i<abc.Length;i++)
{
Response.Write(abc[i]);
Response.Write("<BR>");
}

The GetFileSystemInfos Method is overloaded.  We can pass a search pattern as a string in the form of an optional parameter, which will return the directory and file list containing the name of each file and directory that matches the search pattern.

Listing 30

DirectoryInfo di=new DirectoryInfo(@"E:\TestDirectoryFile ");
FileSystemInfo[] abc=di.GetFileSystemInfos("D*");
for(int i=0;i<abc.Length;i++)
{
Response.Write(abc[i]);
Response.Write("<BR>");
}

In the above code listing all directories and files will be displayed starting with the letter D.

MoveTo Method

MoveTo Method moves a DirectoryInfo instance and its contents to a new path.

Listing 31

di.MoveTo(@"E:\TestDirectoryFile3");
Managing Files

To manage files we have File class and FileInfo class.

File

The File Class provides static methods for the creation, copying, deletion, moving and opening of files.  It also aids in the creation of FileStream objects.  The methods of the File class have been explained in the sections that follow.

AppendText Method

AppendText Method appends text in an existing file as specified in the path.  This method returns a streamwriter object that is used to append contents in the file.

Listing 32

StreamWriter sw=File.AppendText(@"E:\test.txt");
sw.WriteLine("This is line no 4" );
sw.WriteLine("This is line no 5");
sw.WriteLine("This is line no 6");
sw.Close();

Copy Method

Copy Method copies an existing file to a new file.

Listing 33

File.Copy(Server.MapPath("TestDirectoryFile1.doc"),Server.MapPath("TestDirectoryFile2.doc"));

Create Method

Create Method creates a file in the specified path.

Listing 34

File.Create(Server.MapPath("TestFile.doc"));

CreateText Method

CreateText Method opens or creates a new file as specified in the path.  This method returns a streamwriter object that is used to write content in the file.  Contents of the existing file are overwritten provided the file is not in read only mode.

Listing 35

StreamWriter sw=File.CreateText(@"E:\test.txt");
sw.WriteLine("This is line no 1" );
sw.WriteLine("This is line no 2");
sw.WriteLine("This is line no 3");
sw.Close();

Delete Method

Delete Method deletes the specified file.

Listing 36

File.Delete(Server.MapPath("TestFile.doc"));

Exists Method

Exists Method determines whether the specified file exists.

Listing 37

if(File.Exists(Server.MapPath("TestDirectoryFile1.doc")))
{                 
Response.Write("File Exist");
}
else
{
Response.Write("File Does Not Exist");
      
}     

GetCreationTime Method

GetCreationTime Method returns the creation date and time of the file specified in the path.

Listing 38

string str=File.GetCreationTime(@"E:\test.txt").ToString();

GetLastAccessTime Method

GetLastAccessTime Method returns the last access date and time of the specified file in the path.

Listing 39

string str=File.GetLastAccessTime(@"E:\test.txt").ToString();

GetLastWriteTime Method

GetLastWriteTime Method returns the last written date and time in the specified file in the path.

Listing 40

string str=File.GetLastWriteTime(@"E:\test.txt").ToString();

Move Method

Move Method moves a specified file to a new location.

Listing 41

File.Move(Server.MapPath("TestDirectoryFile1.doc"),Server.MapPath("TestDirectoryFile2.doc"));

Open Method

Open Method opens a FileStream on the specified path with read or write access

The syntax is:

File.Open(Server.MapPath("TestDirectoryFile.doc"), FileMode, FileAccess, FileShare);

Once a file is opened and we have FileStream object, we can create a reader or writer object to work with the file’s contents.

The following code listing shows how to write a few lines of text to a file using the StreamWriter Class.

Listing 42

FileStream fs;
StreamWriter sw;
fs=File.Open(@"E:\test.txt",FileMode.Append,FileAccess.Write,FileShare.Write);
sw=new StreamWriter(fs);
sw.WriteLine("Write 1");
sw.WriteLine("Write 2");
sw.WriteLine("Write 3");
sw.Close();

FileInfo

The FileInfo class provides instance methods for the creation, copying, deletion, moving and opening of files.  It also provides members to create FileStream objects.

AppendText Method

AppendText Method appends text in an existing file using StreamWriter object returned by this method.

Listing 43

FileInfo fi=new FileInfo(@"E:\test.txt");
StreamWriter sw=fi.AppendText();
sw.WriteLine("This is a new line");
sw.Close();

CopyTo Method

CopyTo Method copies an existing file to a new file.

Listing XXXXIV

FileInfo fi=new FileInfo(Server.MapPath("TestDirectoryFile.doc"));
fi.CopyTo(Server.MapPath("NewTestDirectoryFile.doc"));

Create Method

Create Method creates a file.

Listing 44

FileInfo fi=new FileInfo(Server.MapPath("TestDirectoryFile.doc"));
fi.Create();

CreateText Method

CreateText Method writes a new text file.

Listing 45

FileInfo fi=new FileInfo(Server.MapPath("TestDirectoryFile.doc"));
fi.CreateText();

Delete Method

Delete Method deletes a file.

Listing 46

FileInfo fi=new FileInfo(Server.MapPath("TestDirectoryFile.doc"));
fi.Delete();

MoveTo Method

Move Method renames or moves an existing file.

Listing 47

FileInfo fi=new FileInfo(Server.MapPath("TestDirectoryFile.doc"));
fi.MoveTo(Server.MapPath("NewTestDirectoryFile.doc"));

Open Method

Open Method opens a file with various read or write and sharing privileges.  Once a file is opened and we have FileStream object, we can create a reader or writer object to work with the file’s contents.

Listing 48

FileStream fs;
StreamWriter sw;
FileInfo fis=new FileInfo(@"E:\TestDirectoryFile\test.txt");
fs=fis.Open(FileMode.Append,FileAccess.Write,FileShare.Write);
sw=new StreamWriter(fs);
sw.WriteLine("Write 1");
sw.WriteLine("Write 2");
sw.WriteLine("Write 3");
sw.Close();
FileAccess Enumeration

FileAccess Enumeration defines constants for read, write, or read/write access to a file.

Read

It defines read access to the file.  Data can be read from the file.  Combine with Write for read or write access.

ReadWrite

It defines read and write access to the file.  Data can be written to and read from the file. 

Write

It defines write access to the file.  Data can be written to the file.  Combine with Read for read or write access. 

FileShare Enumeration

FileShare Enumeration specifies the level of access permitted for a file that is already in use.

Delete

It allows subsequent deleting of a file. 

Inheritable

It makes the file handle inheritable by child processes.  This is not directly supported by Win32.

None

It declines sharing of the current file.  Any request to open the file (by this process or another process) will fail until the file is closed. 

Read

It allows subsequent opening of the file for reading.  If this flag is not specified, any request to open the file for reading (by this process or another process) will fail until the file is closed. However, additional permissions will still be needed to access the file, even if this flag is specified. 

ReadWrite

It allows subsequent opening of the file for reading or writing. If this flag is not specified, any request to open the file for reading or writing (by this process or another process) will fail until the file is closed.  However, additional permissions will still be needed to access the file, even if this flag is specified. 

Write

It allows subsequent opening of the file for writing.  If this flag is not specified, any request to open the file for writing (by this process or another process) will fail until the file is closed. However, additional permissions will still be needed to access the file, even if this flag is specified. 

FileMode Enumeration

Specifies whether the contents of an existing file are preserved or overwritten and whether requests to create an existing file cause an exception.

Append

It opens the file if it exists and seeks to the end of the file, or creates a new file.  FileMode.Append can only be used in conjunction with FileAccess.Write.

Create

It specifies that the operating system should create a new file.  The file will be overwritten if it already exists.

CreateNew

It specifies that the operating system should create a new file.

Open

It specifies that the operating system should open an existing file.  The ability to open the file is dependent on the value of enumeration specified by FileAccess.

OpenCreate

It specifies that the operating system should open a file if it exists.  Otherwise, a new file will be created.

Truncate

It specifies that the operating system should open an existing file.  Once opened, the file should be truncated so that its size is zero bytes.

Suggested Reading
Conclusion

The FileInfo and DirectoryInfo classes enable us to work with a single file or directory.  For the most part they provide equivalent functionality to File and Directory classes, which provide static methods for enumerating Files and Directories, but deal with a single object.

Because all Directory methods and File methods are static, it might be more efficient to use a Directory method and File method rather than a corresponding DirectoryInfo instance method and FileInfo instance method if you want to perform only one action.  Most Directory methods require the path to the directory that you are manipulating and all File methods require the path to the file that you are manipulating.

The static methods of the Directory class and File class perform security checks on all methods. Instance methods of DirectoryInfo class and FileInfo class should be considered instead of the corresponding static methods of the Directory class and File class in case you are going to reuse an object several times and avoiding the overhead of the security checks.



©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-04-23 12:42:36 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search