English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C# FileInfo

 In this section, you will learn how to use the FileInfo class to perform read operations on physical files./Write operation.

The FileInfo class provides the same functionality as the static File class, but you can have more control over the read and write operations of files by writing code manually to read or write bytes from files./Write operations have more control.

Important properties and methods of FileInfo:

PropertiesUsage
DirectoryGet the instance of the parent directory.
DirectoryNameGet the string representing the full path of the directory.
ExistsGet a value that indicates whether the file exists.
ExtensionGet the string representing the file extension.
FullNameGet the full path of the directory or file.
IsReadOnlyGet or set a value that determines whether the current file is read-only.
LastAccessTimeGet or set the time when the current file or directory was last accessed.
LastWriteTimeGet or set the time when the current file or directory was last written.
LengthGet the size of the current file in bytes.
NameGet the name of the file.
MethodUsage
AppendTextCreate a StreamWriter to append text to the file represented by this instance of FileInfo.
CopyToCopy the existing file to a new file without overwriting the existing file.
CreateCreate a file.
CreateTextCreate a StreamWriter to write to a new text file.
DecryptDecrypt the file encrypted by the current account using the Encrypt method.
DeleteDelete the specified file.
EncryptEncrypt the file so that only the account used to encrypt the file can decrypt it.
GetAccessControlGet a FileSecurity object that encapsulates the access control list (ACL) entries of the specified file.
MoveToMove the specified file to a new location and provide the option to specify a new file name.
OpenOpen one in the specified FileMode.
OpenReadCreate a read-only FileStream.
OpenTextCreate a file with UTF8An encoded StreamReader, the encoder of which can read from an existing text file.
OpenWriteCreate a write-only FileStream.
ReplaceReplace the content of the specified file with the file described by the current FileInfo object, delete the original file, and create a backup of the replacement file.
ToStringto return the path as a string.

The following example shows how to manually read bytes from a file and then use UTF8Encoding will convert them to strings:

Example: Using FileInfo class to read a file

//Create FileInfo object 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 a byte array of the same size as the FileStream length
byte[] fileBytes = new byte[fs.Length];
//Define a counter to check how many bytes to read. Decrease the counter when reading each byte
int numBytesToRead = (int)fileBytes.Length;
//The counter indicates the number of bytes read
int numBytesRead = 0;
//Iterate until all bytes are read from FileStream
while (numBytesToRead > 0)
{
    int n = fs.Read(fileBytes, numBytesRead, numBytesToRead);
        
    if (n == 0)
        break;
    numBytesRead += n;
    numBytesToRead -= n;
}
//After reading all bytes from FileStream, you can use UTF8encoding to convert it to a string
string filestring = Encoding.UTF8.GetString(fileBytes);

As shown in the above code, you must write a lot of code to read from FileSream/Write strings. However, using StreamReader and StreamWriter can easily complete the same read/Write operation.

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

Example: Using StreamReader to read a file

//Create FileInfo object 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 a StreamReader object by passing the FileStream object that needs to be operated on
StreamReader sr = new StreamReader(fs);
//Use the ReadToEnd method to read all content from the file
string fileContent = sr.ReadToEnd();
//Close the StreamReader object after the operation
sr.Close();
fs.Close();

Note, fi.Open() has three parameters:

  • The first parameter is FileMode, used to create and open a file (if the file does not exist);

  • The second parameter FileAccess represents read operations;

  • The third parameter is to share the file with other users for reading when opening the file.

The following example shows how StreamWriter makes it easier to write strings to a file:

Example: Use StreamWriter to write text to a file

//Create FileInfo object 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 a StreamWriter object to write strings to FileStream
StreamWriter sw = new StreamWriter(fs);
sw.WriteLine("Another line from streamwriter");
sw.Close();

You cannot perform both read and write operations on the same FileStream object. If you are already reading a file, please create a separate FileStream object to write to the same file as follows:

Example: StreamReader and 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 StreamWriter
StreamReader sr = new StreamReader(fsToRead);
//Use the StreamReader object to read all text
string fileContent = sr.ReadToEnd();
sr.Close();
//Get 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();

Therefore, you can use FileInfo, StreamReader, and StreamWriter classes to read from physical files/Write content.