C# FileInfo:

You have learned how to perform different tasks on physical files using static File class in the previous section. Here, we will use FileInfo class to perform read/write operation on physical files.

The FileInfo class provides the same functionality as the static File class but you have more control on read/write operations on files by writing code manually for reading or writing bytes from a file.

Important properties and methods of FileInfo:

Property Usage
Directory Gets an instance of the parent directory.
DirectoryName Gets a string representing the directory's full path.
Exists Gets a value indicating whether a file exists.
Extension Gets the string representing the extension part of the file.
FullName Gets the full path of the directory or file.
IsReadOnly Gets or sets a value that determines if the current file is read only.
LastAccessTime Gets or sets the time the current file or directory was last accessed
LastWriteTime Gets or sets the time when the current file or directory was last written to
Length Gets the size, in bytes, of the current file.
Name Gets the name of the file.
Method Usage
AppendText Creates a StreamWriter that appends text to the file represented by this instance of the FileInfo.
CopyTo Copies an existing file to a new file, disallowing the overwriting of an existing file.
Create Creates a file.
CreateText Creates a StreamWriter that writes a new text file.
Decrypt Decrypts a file that was encrypted by the current account using the Encrypt method.
Delete Deletes the specified file.
Encrypt Encrypts a file so that only the account used to encrypt the file can decrypt it.
GetAccessControl Gets a FileSecurity object that encapsulates the access control list (ACL) entries for a specified file.
MoveTo Moves a specified file to a new location, providing the option to specify a new file name.
Open Opens a in the specified FileMode.
OpenRead Creates a read-only FileStream.
OpenText Creates a StreamReader with UTF8 encoding that reads from an existing text file.
OpenWrite Creates a write-only FileStream.
Replace Replaces the contents of a specified file with the file described by the current FileInfo object, deleting the original file, and creating a backup of the replaced file.
ToString Returns a path as string.

The following example shows how to read bytes from a file manually and then convert them to a string using UTF8 encoding:

Example: Read file using FileInfo class

//Create object of FileInfo for specified path            
FileInfo fi = new FileInfo(@"D:\DummyFile.txt");

//Open file for Read\Write
FileStream fs = fi.Open(FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite); 

//create byte array of same size as FileStream length
byte[] fileBytes = new byte[fs.Length];

//define counter to check how much butes to read. Decrease the counter as you read each byte
int numBytesToRead = (int)fileBytes.Length;

//Counter to indicate number of bytes already read
int numBytesRead = 0;

//iterate till all the bytes read from FileStream
while (numBytesToRead > 0)
{
    int n = fs.Read(fileBytes, numBytesRead, numBytesToRead);
    if (n == 0)
        break;

    numBytesRead += n;
    numBytesToRead -= n;
}

//Once you read all the bytes from FileStream, you can convert it into string using UTF8 encoding
string filestring = Encoding.UTF8.GetString(fileBytes);

As you have seen in the above code, you have to write lot of code for reading/writing a string from a FileSream. The same read/write operation can be done easily using StreamReader and StreamWriter.

The following example shows how StreamReader makes it easy to read strings from a file:

Example: Read file using StreamReader

//Create object of FileInfo for specified path            
FileInfo fi = new FileInfo(@"D:\DummyFile.txt");
        
//Open file for Read\Write
FileStream fs = fi.Open(FileMode.OpenOrCreate, FileAccess.Read , FileShare.Read); 

//Create object of StreamReader by passing FileStream object on which it needs to operates on
StreamReader sr = new StreamReader(fs);

//Use ReadToEnd method to read all the content from file
string fileContent = sr.ReadToEnd();

//Close StreamReader object after operation
sr.Close();
fs.Close();

Notice that fi.Open() has three parameters: The first parameter is FileMode for creating and opening a file if it does not exist; the second parameter, FileAccess, is to indicate a Read operation; and the third parameter is to share the file for reading with other users while the file is open.

The following example shows how StreamWriter makes it easy to write strings to a File:

Example: Write texts to file using StreamWriter

//Create object of FileInfo for specified path            
FileInfo fi = new FileInfo(@"D:\DummyFile.txt");
        
//Open file for Read\Write
FileStream fs = fi.Open(FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read ); 

//Create StreamWriter object to write string to FileSream
StreamWriter sw = new StreamWriter(fs);
sw.WriteLine("Another line from streamwriter");
sw.Close();

Read and Write operations are not possible on the same FileStream object simultaneously. If you are already reading from a file, create a separate FileStream object to write to the same file, as shown below:

Example: StreamReader & StreamWriter

//Create FileInfo object for DummyFile.txt
FileInfo fi = new FileInfo(@"D:\DummyFile.txt");

//open DummyFile.txt for read operation
FileStream fsToRead = fi.Open(FileMode.OpenOrCreate, FileAccess.ReadWrite , FileShare.ReadWrite); 

//open DummyFile.txt for write operation
FileStream fsToWrite = fi.Open(FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite); 
          
//get the StreamReader

StreamReader sr = new StreamReader(fsToRead);
//read all texts using StreamReader object
string fileContent = sr.ReadToEnd();
sr.Close();

//get the StreamWriter
StreamWriter sw = new StreamWriter(fsToWrite);
//write some text using StreamWriter
sw.WriteLine("Another line from streamwriter");
sw.Close();

//close all Stream objects
fsToRead.Close();
fsToWrite.Close();

Thus you can use FileInfo, StreamReader and StreamWriter class to read/write contents from physical file.

Further Reading:

Points to Remember :

  1. Use FileInfo class to perform operations on physical files manually.
  2. Use StreamReader & StreamWriter class with FileInfo for reading or writing string from physical file.

Learn about C# exceptions next