C# Simplified, part 5: Error Handling and Files - Accessing files and directories
(Page 4 of 8 )
You can access files and directories with the help of System.IO namespace. This namespace provides all the necessary classes, methods and properties for manipulating files and directories. The main classes within this namespace are listed in table 5.2
Table 5.2
Class Name | Usage |
BinaryReader and BinaryWriter | To read and write primitive data types. |
Directory, File, DirectoryInfo and FileInfo | To create, delete, move files and directories. Also used for getting specific information about the files with the help of various properties. |
FileStream | To access files in a random fashion. |
MemoryStream | To access data stored in memory. |
StreamWriter and StreamReader | To read and write textual Information. |
StringReader and StringWriter | To read and write textual information from a string buffer. |
Working with FileInfo and DirectoryInfo classes
FileSystemInfo is the base class of FileInfo and DirectoryInfo classes. FileSystemInfo is an abstract class. This means that you can’t instantiate this class directly. You can create instances of the classes inheriting from it and also make use of the various properties and methods. Table 5.3 lists some of the important properties of the FileSystemInfo class
Table 5.3
Properties | Usage |
Attributes | Returns attributes associated with a file. Takes FileAttributes enumeration values. |
CreationTime | Returns the time of creation of the file. |
Exists | Used to check if a supplied file is a directory or not. |
Extension | Used to return the file extension. |
LastAccessTime | Returns last accessed time of the file or the directory. |
FullName | Returns the full path of the file or the directory. |
LastWriteTime | Returns the time of last written activity to the file. |
Name | Returns the name of a given file. |
Delete() | This method is used to delete a file. |
Listing 5.4 creates an instance of the DirectoryInfo class, and the code in listing 5.5 shows how to apply some of the above properties.
Listing 5.4
DirectoryInfo dirinfo = new DirectoryInfo(@”C:\WINDOWS”);
Listing 5.5
using System;
using System.IO;
class DirectoryDemo
{
public static void Main()
{
DirectoryInfo dirinfo = new DirectoryInfo(@"C:\WINDOWS");
FileInfo finfo = new FileInfo("D:\Test.txt");
Console.WriteLine("Full Name is: {0}", dirinfo.FullName);
Console.WriteLine("Time of Creation : {0}", dirinfo.CreationTime);
Console.WriteLine("Attributes are : {0}", dirinfo.Attributes.ToString());
Console.WriteLine("Full Name is: {0}", finfo.FullName);
}
}
Next: Displaying all files under a directory >>
More C# Articles
More By Anand Narayanaswamy