In Focus

File I/O Using C#

In this article, you will learn how to work with classes in the System.IO namespace for reading data from and writing data to files.

File handling is a very crucial and important feature for many enterprise applications around us. To support this feature Microsoft .NET Framework offers the System.IO namespace, that provides various classes to enable the developers to do I/O.

In this article, you will learn how to work with classes in the System.IO namespace for reading data from and writing data to files. The System.IO namespace also provides features to support manipulation of files and directories of the operating system’s file system.

Objectives

  • Using the File class for reading and writing data.
  • Using the File and FileInfo class to manipulate files.
  • Using the DirectoryInfo and Directory classes to manipulate directories.

Using the File class for reading and writing data.

The File class of the System.IO namespace offers various static methods that enable a developer to do direct reading and writing of files. Typically, to read data from a file, you:

  1. Get a hold on the file handle.
  2. Open a stream to the file.
  3. Buffer the file data into memory.
  4. Release the hold of file handle once done.

Reading Data from Files

The following list describes some of these methods:

  • The "ReadAllText" method reads the data of a file.
        

    string filePath = @"C:\MyData\TestFile.txt";

    string testData = File.ReadAllText(filePath);
     

  • The "ReadAllLines" method reads all the contents of a file and stores each line at a new index in an array of string type.
     

    string filePath = @"C:\MyData\TestFile.txt";

    string[] testDataLineByLine = File.ReadAllLines(filePath);
     

  • The "ReadAllBytes" method reads the contents of a file as binary data and stores the data in a byte array.

    string filePath = @"C:\MyData\TestFile.txt";
    byte[] testDataRawBytes = File.ReadAllBytes(filePath);

Each of these methods enable the developer to read the contents of a file and load into memory. The ReadAllText method will enable the developer to cache the entire file in memory via a single operation. Whereas the ReadAllLines method will read line-by-line into an array.

Writing Data to Files

The File class also provides methods for writing various types of data to a file. For each of the various types of data you can write, the File class provides two methods.

If the specified file does not exist, then the Writexxx methods create a new file with the new data. If the file does exist then the Writexxx methods overwrite the existing file with the new data.

If the specified file does not exist then the Appendxxx methods also create a new file with the new data.

However, if the file does exist then the new data is written to the end of the existing file.

The following list describes some of these methods:

  • The "WriteAllText" method enables the developers to write the contents of string variable into a file. If the file exists, its contents will be overwritten. The following code example shows how to write the contents of a string named settings to a new file named settings.txt.

       string filePath = @"C:\MyData\TestFile.txt";

       string data = "C# Corner MVP & Microsoft MVP;";

       File.WriteAllText(filePath, data);
     

  • The "WriteAllLines" method enables the developers to write the contents of a string array to a file. Each entry in the string array will be a new line in the new file.

    string filePath = @"C:\MyData\TestFile.txt";
    string[] data = { "MCT", "MCPD", "MCTS", "MCSD.NET", "MCAD.NET", "CSM" };
    File.WriteAllLines(filePath, data);
     
  • The "AppendAllText" method enables the developers to write the contents of a string variable at the end of an existing file.

    string filePath = @"C:\MyData\TestFile.txt";
    string data = "Also Certified from IIT Kharagpur";
    File.AppendAllText(filePath, data);
     
  • The "AppendAllLines" method enables the developers to write the contents of a string array to the end of an existing file.

    string filePath = @"C:\MyData\TestFile.txt";
    string[] otherData = { "Worked with Microsoft", "Lived in USA" };
    File.AppendAllLines(filePath, otherData);

File and FileInfo class to Manipulating Files

File manipulation is as important as file creation. Many applications typically require the ability to interact with files stored on the file system. For example, copying a file from a directory to another location for further processing.

Developers can implement this type of functionality by using the File and FileInfo classes.

Using File class to manipulate files

The File class consists of various static methods that a developer can use to perform basic file manipulation. The following list describes some of those methods.

The "Copy" method enables the developers to copy an existing file to a different directory location on the file system.

string sourceFilePath = @"C:\MyData\TestFile.txt";
string destinationFilePath = @"C:\temp\Data.txt";
bool overWrite = true;
File.Copy(sourceFilePath, destinationFilePath, overWrite);

Note: The overwrite parameter passed to the Copy method call indicates that the copy process should overwrite an existing file if it exists at the destination path. If you pass false to the Copy method call, and the file already exists then the Common Language Runtime (CLR) will throw a System.IO.IOException.

  • The "Delete" method deletes an existing file from the file system.

    string sourceFilePath = @"C:\MyData\TestFile.txt";
    File
    .Delete(sourceFilePath);

     
  • The "Exists" method checks whether a file exists on the file system.

    string sourceFilePath = @"C:\MyData\TestFile.txt";

    bool doesFileExist = File.Exists(sourceFilePath);
     

  • The "GetCreationTime" method obtains the date time stamp that describes when a file was created, from the metadata associated with the file.

    string sourceFilePath = @"C:\MyData\TestFile.txt";
    DateTime fileCreatedOn = File.GetCreationTime(sourceFilePath);

Using FileInfo class to manipulate files

Unlike the File class the FileInfo class provides instance members that you can use to manipulate an existing file. Also in contrast to the File class that provides static methods for direct manipulation, the FileInfo class works like an in memory representation of the physical file.

Instantiating the FileInfo Class

string sourceFilePath = @"C:\MyData\TestFile.txt";
FileInfo fInfo = new FileInfo(sourceFilePath);

Once the instance of the FileInfo class is created, you can use the properties and methods to interact with the file. The following list describes some of these properties and methods.

The "CopyTo" method enables the developers to copy an existing file to a different directory on the file system.     

string sourceFilePath = @"C:\MyData\TestFile.txt";
string destinationFilePath = @"C:\temp\Data.txt";
bool overwrite = true;
FileInfo
fInfo = new FileInfo(sourceFilePath);
fInfo.CopyTo(destinationFilePath, overwrite);

Note: The overwrite parameter in the CopyTo method indicates that the copy process should overwrite an existing file if it exists at the specified destination file path. If you pass false to the CopyTo method, and the file already exists then the CLR will throw a System.IO.IOException.

  • The "Delete" method enables the developers to delete a file.
           

          string sourceFilePath = @"C:\MyData\TestFile.txt";
    FileInfo fInfo = new FileInfo(sourceFilePath);
    fInfo.Delete();
     

  • The "DirectoryName" property enables the developers to get the directory path to the file.

    string sourceFilePath = @"C:\MyData\TestFile.txt";
    FileInfo
    fInfo = new FileInfo(sourceFilePath);
    string directoryPath = fInfo.DirectoryName;
    // returns C:\MyData
     
  • The "Exists" method enables the developers to determine if the specified file exists within the file system.

    string sourceFilePath = @"C:\MyData\TestFile.txt";
    FileInfo fInfo = new FileInfo(sourceFilePath);
    bool filesExists = fInfo.Exists;
     
  • The "Extension" property enables you to get the file extension of a file.

    string sourceFilePath = @"C:\MyData\TestFile.txt";
    FileInfo fInfo = new FileInfo(sourceFilePath);
    bool filesExtn = fInfo.Extension;
     
  • The "Length" property enables the developers to get the length of the file in bytes.

    string sourceFilePath = @"C:\MyData\TestFile.txt";
    FileInfo fInfo = new FileInfo(sourceFilePath);
    long length = fInfo.Length;

DirectoryInfo and Directory class to Manipulating Directories

In an operating system’s file system, the files are organized into directories. Hence, it is very crucial for an application to interact and manipulate the file system’s directory structure. Interaction with directories may include checking that a directory exists before writing a file or to remove directories after the process is complete as a cleanup policy. The .NET Framework class library provides the Directory and DirectoryInfo classes for such operations.

Using Directory class to manipulate directories

Similar to the File class, the "Directory" class provides static methods that enable you to interact with directories, without instantiating a directory-related object in your code.

  • The "CreateDirectory" method creates a new directory on the file system.

    string sourceDirPath = @"C:\MyData\Data";
    Directory.CreateDirectory(sourceDirPath);
     
  • The "Delete" method deletes a directory at a specific path.

    string sourceDirPath = @"C:\MyData\Data";
    bool deleteRecursively = true;
    Directory.Delete(sourceDirPath, deleteRecursively);

    Note: The deleteRecursively parameter passed into the Delete method specifies whether the delete process should delete any content that may exist in the directory. If you pass false into the Delete method, and the directory is not empty then the CLR will throw a System.IO.IOException.|
     
  • The "Exists" method determines if a directory exists on the file system.

    string sourceDirPath = @"C:\MyData\Data";
    bool tempDataDirectoryExists = Directory.Exists(sourceDirPath);
     
  • The "GetDirectories" method gets a list of all subdirectories within a specific directory on the file system.

    string sourceDirPath = @"C:\MyData\Data";
    string[] subDirectories = Directory.GetDirectories(sourceDirPath);
     
  • The "GetFiles" method gets a list of all the files within a specific directory on the file system.
     
    string sourceDirPath = @"C:\MyData\Data";
    string[] files = Directory.GetFiles(sourceDirPath);

The "DirectoryInfo" class provides instance members that enable you to access directory metadata and manipulate the directory structure.

Using DirectoryInfo class to manipulate directories.

The "DirectoryInfo" class acts as an in-memory representation of a directory. Before you can access the properties and execute the methods that the DirectoryInfo class exposes, you must create an instance of the class.
 
Instantiating the DirectoryInfo Class

string sourceDirPath = @"C:\MyData\Data";
DirectoryInfo directory = new DirectoryInfo(sourceDirPath);

When you have created an instance of the DirectoryInfo class, you can then use its properties and methods to interact with the directory. The following list describes some of these properties and methods:

  • The "Create" method creates a new directory on the file system.

    string sourceDirPath = @"C:\MyData\Data";
    DirectoryInfo directory = new DirectoryInfo(sourceDirPath);
    directory.Create();
     
  • The "Delete" method deletes a directory at a specific path.

    string sourceDirPath = @"C:\MyData\Data";
    bool deleteRecursively = true;
    DirectoryInfo directory = new DirectoryInfo(sourceDirPath);
    directory.Delete(deleteRecursively);

    Note: The recursivelyDeleteSubContent parameter passed to the Delete method call indicates whether the delete process should delete any content that may exist in the directory. If you pass false to the Delete method call, and the directory is not empty then the CLR will throw a System.IO.IOException.
     

  • The "Exists" property determines if a directory exists on the file system.

    string sourceDirPath = @"C:\MyData\Data";
    DirectoryInfo directory = new DirectoryInfo(sourceDirPath);
    bool directoryExists = directory.Exists
     
  • The "FullName" property gets the full path to the directory. The following example shows how to get the full path to the tempData directory.

    string sourceDirPath = @"C:\MyData\Data";          
    DirectoryInfo directory = new DirectoryInfo(sourceDirPath);
    string fullPath = directory.FullName;
     
  • The "GetDirectories" method gets a list of all subdirectories within a specific directory on the file system. In contrast to the static File.GetDirectories method, this instance method returns an array of type DirectoryInfo, that enables you to use each of the instance properties for each subdirectory.

    string sourceDirPath = @"C:\MyData\Data";
    DirectoryInfo directory = new DirectoryInfo(sourceDirPath);
    DirectoryInfo[] subDirectories = directory.GetDirectories();

     

  • The "GetFiles" method gets a list of all the files within a specific directory on the file system. In contrast to the static File.GetFiles method, this instance method returns an array of type
    FileInfo, that enables you to use each of the instance properties for each file.

    string sourceDirPath = @"C:\MyData\Data";
    DirectoryInfo directory = new DirectoryInfo(sourceDirPath);
    FileInfo[] subFiles = directory.GetFiles();

Depending on whether you require a simple one-line-of-code approach to manipulate a directory, or something that offers slightly more flexibility, either the static Directory or instance DirectoryInfo class should fulfill your requirements.