AspAlliance.com LogoASPAlliance: Articles, reviews, and samples for .NET Developers
URL:
http://aspalliance.com/articleViewer.aspx?aId=1361&pId=-1
Working with Directories and Files in .NET
page
by Joydip Kanjilal
Feedback
Average Rating: 
Views (Total / Last 10 Days): 26815/ 51

Introduction

Microsoft .NET allows you to read and write files in your file system provided you have set the necessary permissions. One of the most powerful things that Microsoft .NET provides you is its rich Base Class Library that gives you enormous flexibility to do anything that you can think of. The Base Class Library of the Microsoft .NET Framework class is actually a library of classes, interfaces that are included as a part of the in the Microsoft .NET Framework Software Developer's Kit (SDK). A directory is a special type of file that can contain other files and/or directories. Hence, we will start our discussion with how we can work with directories in C# followed by a discussion on how we can use C# to read and write files to and from the file system.

The Directory, DirectoryInfo, File and FileInfo classes in the .NET Base Class Library provide a simplified and powerful access to the files and directories in your system.

The names of the members of the Directory, DirectoryInfo, File and the FileInfo classes are self explanatory. I have shaved off the unnecessary discussion on the members of these classes that have names that correspond to their respective purposes. I hoped that the readers would be able to understand them with ease; still, you can always refer to MSD for more information.

The following sections discuss each of the above classes and its members and how they can be used to work with files and directories from within Microsoft .NET’s managed environment.

Working with directories

A directory, as we learned earlier, is a special type of a file. Both files and directories are stored in the permanent storage device of your computer system, abiding by the protocols as laid out by the file system of the host Operating System. But what is a file system, anyway? A file system is the format and rules and regulations that are set by the host Operating System of your computer system that specifies how the files and directories in your system are organized. The file system of MSDOS is FAT, Windows 9x is VFAT and the same of Windows XP or Windows NT is NTFS and that of UNIX is UFS.

For working with directories in .NET, you have two classes in the .NET Base Class Library. These classes are the Directory class and the DirectoryInfo class and are present in the System.IO namespace. The System.IO namespace contains a list of classes, methods and properties for accessing the files and directories in the file system and working with them. You can use the classes in the System.IO namespace to read and write files, list directories, get file information, and manipulate files and directories. According to MSDN, "The System.IO namespace contains types that allow reading and writing to files and data streams and types that provide basic file and directory support." The System.IO namespace contains the following classes.

·         TextReader

·         TextWriter

·         StringReader

·         StringWriter

·         BinaryReader

·         BinaryWriter

·         StreamReader

·         StreamWriter

·         File

·         FileInfo

·         Directory

·         DirectoryInfo

Let us start our discussion with the Directory class. We will follow this up with a discussion on the DirectoryInfo class. You have a number of static methods in the Directory class for working with directories. All these methods are static methods and they require a security check that in turn verifies whether the user has the necessary permission to access the file system from within the .NET’s managed environment.

The members of the Directory class in the .NET Base Class Library are:

·         Exists

·         CreateDirectory

·         Delete

·         Move

·         SetCreationTime

·         GetCreationTime

·         SetLastAccessTime

·         GetLastAccessTime

·         SetLastWriteTime

·         GetLastWriteTime

·         GetLogicalDrives

·         GetParent

·         GetCurrentDirectory

·         GetDirectoryRoot

·         GetDirectories

·         GetFiles

·         GetFileSystemEntries

The DirectoryInfo class is similar to the Directory class with the exception that it contains only static methods. The methods of the DirectoryInfo class are as follows.

·         Create

·         CreateSubDirectory

·         MoveTo

·         Delete

·         GetFiles

·         GetDirectories

·         GetFileSystemInfos

The following code snippet illustrates how you can use the Directory class to display the list of files and directories.

Listing 1

string[] files = Directory.GetFileSystemEntries(Environment.GetFolderPath
  (Environment.SpecialFolder.Personal));
 
  string[] directories = Directory.GetDirectories (Environment.GetFolderPath
    (Environment.SpecialFolder.ProgramFiles));
  foreach (string file in files)
  {
    System.WriteLine(file);
  }
 
foreach (string directory in directories)
  {
    System.WriteLine(directory);
  }
Working with Files

Similar to the Directory and the DirectoryInfo class that we use when working with Directories, you have the File and the FileInfo classes for working with files in C#. The File class contains a number of static methods that can be used for creating, opening, copying, deleting, and moving of files in your file system. The members of the File class are as follows.

·         Copy

·         Exists

·         Open

·         Delete

·         Move

·         Create

·         CreateText

·         AppendText

·         GetCreationTime

·         GetLastAccessTime

·         GetLastWriteTime

The following code snippet illustrates how you can use the File class to check whether a file exists and if so, it sets the creation time, last access time and the last write time of the file. It then deletes the file using the Delete() method of the File class.

Listing 2

if (File.Exists(@"C:\Test.txt"))
  {
   File.SetCreationTime(@"C:\Test.txt", Date.Now);
   File.SetLastAccessTime(@"C:\Test.txt", Date.Now);
   File.SetLastWriteTime(@"C:\Test.txt", Date.Now);
  }
 
  if (File.Exists(@"C:\Test.txt"))
   File.Delete(@"C:\Test.txt");

Please note that I have provided you some of the most important members of the classes Directory, DirectoryInfo, File and FileInfo. You can refer to MSDN for a complete list of the members of each of these classes.

Unlike the File class, the FileInfo class contains not only static methods, but the FileInfo class also contains instance methods to perform various file operations in your file system. Note that the FileInfo class is abstract in nature. The following is the list of members of the FileInfo class.

·         Open

·         Create

·         Delete

·         CopyTo

·         MoveTo

·         CreateText

·         AppendText

Further to this, you have some enumerators that contain fields that correspond to the file modes, file share and the file access permissions, etc. The following is the complete list of the enumerators in the System.IO namespace.

·         DriveType

·         FileAccess

·         FileAttributes

·         FileMode

·         FileOption

·         FileShare

·         NotifyFilters

·         SearchOption

·         SeekOrigin

·         WatcherChangeTypes

I will discuss only the FileMode, FileShare, and FileAccess enumerators here. You can refer to the MSDN for information on the other enumerators.

The available file modes that are contained in the FileMode enumerator are the following.

·         Open

·         Truncate

·         Create

·         CreateNew

·         Append

The truncate file mode is used to indicate that an existing file should be opened and the contents of the file should be truncated so that its size becomes bytes. I will skip a discussion on the other file modes as their names are self explanatory and should be well understood by the reader. The FileShare enumerator is used to specify the level of access for a file in the file system that is currently in use. The FileShare enumerator, "Contains constants for controlling the kind of access other FileStream objects can have to the same file." The available fields in the FileShare enumerator are listed here.

·         None

·         Read

·         ReadWrite

·         Delete

·         Write

The FileAccess enumerator contains fields that correspond to read, write and read/write access to a file in the file system. The following are the fields in the FileAccess enumerator.

·         Read

·         Write

·         ReadWrite

Points to remember

The most important point that one should keep in mind when working with files and directories in .NET is the necessary permissions that are required for the user. It should be noted that the static methods of the File and the Directory classes require a security check for them to operate; this hampers the performance a bit. I would recommend using the FileInfo and the DirectoryInfo classes over the File and the DirectoryInfo classes if you have a lot of operations to perform on the files and the directories in your file system.

Suggested Readings
Conclusion

I hope this article will serve as a ready guide to the readers who are interested in working with files and directories in .NET. I have provided the list of the most important members of the classes responsible for dealing with files and directories from within .NET's managed environment. The names of the members of the Directory, DirectoryInfo, File and the FileInfo classes are self explanatory. I hope it was not a problem for the readers to understand the purpose of these members. Still, you can refer to MSDN for a complete reference on all the members of the File, FileInfo, Directory and DirectoryInfo classes that we have had a look at in this article. Readers’ comments and suggestions are welcome. Happy reading!



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