FileInfo In C#

The C# FileInfo provides methods to work with files. In this article, you'll learn how to use FileInfo in C#.

Introduction

The FileInfo class in the .NET and C# provides functions to work with files. This code sample in this tutorial covers most of the functionality provided by the class such as getting a file properties such as file size, creation time, last updated, ready only, file exists and so on. The tutorial also covers how to create a file, read a file, move, replace, and delete a file using C# and .NET. 

Create a FileInfo

A FileInfo object is created using the default constructor that takes a string as a file name with a full path.

  1. string fileName = @"C:\Temp\MaheshTXFI.txt";     
  2. FileInfo fi = new FileInfo(fileName);

FileInfo Properties

The FileInfo class provides properties to get file name, extension, directory, size and file attributes.

Get File Name

The FileName property returns just the file name part of the full path of a file. The following code snippet returns the file name.

  1. string justFileName = fi.Name;   
  2. Console.WriteLine("File Name: {0}", justFileName);

Get Full Path of a File

The FullName property returns just the full path of a file including the file name. The following code snippet returns the full path of a file.

  1. string fullFileName = fi.FullName;     
  2. Console.WriteLine("File Name: {0}", fullFileName);

Get a File Extension

The Extension property returns the extension of a file. The following code snippet returns the extension of a file.

  1. string extn = fi.Extension;     
  2. Console.WriteLine("File Extension: {0}", extn);

Get Directory Name of a File

The DirectoryName property returns the name of the directory of a file. The following code snippet returns the directory of a file.

  1. string directoryName = fi.DirectoryName;    
  2. Console.WriteLine("Directory Name: {0}", directoryName);

Check if a File Exists

The Exists property returns true if a file exists. The following code snippet returns true if a file already exists.

  1. bool exists = fi.Exists;

Get a file size

The Length property returns the size of a file in bytes. The following code snippet returns the size of a file.

  1. // Get file size    
  2. long size = fi.Length;    
  3. Console.WriteLine("File Size in Bytes: {0}", size);

Check if a file is read-only

The IsReadOnly property returns if a file is read only. The following code snippet returns true if a file is read only.

  1. // File ReadOnly ?      
  2. bool IsReadOnly = fi.IsReadOnly;     
  3. Console.WriteLine("Is ReadOnly: {0}", IsReadOnly);

File Creation Time

The CreationTime property returns the DateTime when a file was creaed. The following code snippet returns the creation time of a file.

  1. // Creation, last access, and last write time      
  2. DateTime creationTime = fi.CreationTime;     
  3. Console.WriteLine("Creation time: {0}", creationTime);

File Last Access Time

The LastAccessTime property returns the DateTime when a file was last accessed. The following code snippet returns the last access time of a file.

  1. DateTime accessTime = fi.LastAccessTime;     
  2. Console.WriteLine("Last access time: {0}", accessTime);

File Last Updated Time

The LastWriteTime property returns the DateTime when a file was last updated or written. The following code snippet returns the last write time of a file.

  1. DateTime updatedTime = fi.LastWriteTime;     
  2. Console.WriteLine("Last write time: {0}", updatedTime);     

Sample

Here is a complete sample.

  1. // Full file name      
  2. string fileName = @"C:\Temp\MaheshTXFI.txt"; FileInfo fi = new FileInfo(fileName);    
  3. // Create a new file      
  4. using (FileStream fs = fi.Create())    
  5. {    
  6.     Byte[] txt = new UTF8Encoding(true).GetBytes("New file.");    
  7.     fs.Write(txt, 0, txt.Length);    
  8.     Byte[] author = new UTF8Encoding(true).GetBytes("Author Mahesh Chand");    
  9.     fs.Write(author, 0, author.Length);    
  10. }    
  11. // Get File Name      
  12. string justFileName = fi.Name; Console.WriteLine("File Name: {0}", justFileName);    
  13. // Get file name with full path      
  14. string fullFileName = fi.FullName; Console.WriteLine("File Name: {0}", fullFileName);    
  15. // Get file extension      
  16. string extn = fi.Extension; Console.WriteLine("File Extension: {0}", extn);    
  17. // Get directory name      
  18. string directoryName = fi.DirectoryName; Console.WriteLine("Directory Name: {0}", directoryName);    
  19. // File Exists ?      
  20. bool exists = fi.Exists;    
  21. Console.WriteLine("File Exists: {0}", exists);    
  22. if (fi.Exists)    
  23. {    
  24.     // Get file size      
  25.     long size = fi.Length;    
  26.     Console.WriteLine("File Size in Bytes: {0}", size);    
  27.     // File ReadOnly ?      
  28.     bool IsReadOnly = fi.IsReadOnly; Console.WriteLine("Is ReadOnly: {0}", IsReadOnly);    
  29.     // Creation, last access, and last write time      
  30.     DateTime creationTime = fi.CreationTime;    
  31.     Console.WriteLine("Creation time: {0}", creationTime);    
  32.     DateTime accessTime = fi.LastAccessTime;    
  33.     Console.WriteLine("Last access time: {0}", accessTime);    
  34.     DateTime updatedTime = fi.LastWriteTime;    
  35.     Console.WriteLine("Last write time: {0}", updatedTime);    
  36. }

Create a File

We can create a file in two different following methods

  • File.Create
  • File.CreateText

FileInfo.Create Method

The FileInfo.Create method creates a file at the given path. If just a file name is provided without a path, the file will be created in the current folder.

The following code snippet creates a file using the Create method that returns a FileSteam object. The Write method of FileStream can be used to write text to the file.

  1. // Full file name      
  2. string fileName = @"C:\Temp\MaheshTXFI.txt";    
  3. FileInfo fi = new FileInfo(fileName);    
  4. try    
  5. {    
  6.     // Check if file already exists. If yes, delete it.     
  7.     if (fi.Exists)    
  8.     {    
  9.         fi.Delete();    
  10.     }    
  11.     // Create a new file      
  12.     using (FileStream fs = fi.Create())    
  13.     {    
  14.         Byte[] txt = new UTF8Encoding(true).GetBytes("New file.");    
  15.         fs.Write(txt, 0, txt.Length);    
  16.         Byte[] author = new UTF8Encoding(true).GetBytes("Author Mahesh Chand");    
  17.         fs.Write(author, 0, author.Length);    
  18.     }    
  19.     // Write file contents on console.      
  20.     using (StreamReader sr = File.OpenText(fileName))    
  21.     {    
  22.         string s = "";    
  23.         while ((s = sr.ReadLine()) != null)    
  24.         {    
  25.             Console.WriteLine(s);    
  26.         }    
  27.     }    
  28. }    
  29. catch (Exception Ex)    
  30. {    
  31.     Console.WriteLine(Ex.ToString());    
  32. }

FileInfo.CreateText Method

The FileInfo.CreateText method creates and opens a file for writing UTF-8 encoded text. If file already exists, this method opens the file.

The following code snippet creates a file using the CreateText method that returns a StreamWriter object. The WriteLine method of SteamLine can be used to add line text to the object and writes to the file.

  1. // Full file name      
  2. string fileName = @"C:\Temp\MaheshTXFITx.txt";    
  3. FileInfo fi = new FileInfo(fileName);    
  4. try    
  5. {    
  6.     // Check if file already exists. If yes, delete it.     
  7.     if (fi.Exists)    
  8.     {    
  9.         fi.Delete();    
  10.     }    
  11.     // Create a new file      
  12.     using (StreamWriter sw = fi.CreateText())    
  13.     {    
  14.         sw.WriteLine("New file created: {0}", DateTime.Now.ToString());    
  15.         sw.WriteLine("Author: Mahesh Chand");    
  16.         sw.WriteLine("Add one more line ");    
  17.         sw.WriteLine("Add one more line ");    
  18.         sw.WriteLine("Done! ");    
  19.     }    
  20.     // Write file contents on console.      
  21.     using (StreamReader sr = File.OpenText(fileName))    
  22.     {    
  23.         string s = "";    
  24.         while ((s = sr.ReadLine()) != null)    
  25.         {    
  26.             Console.WriteLine(s);    
  27.         }    
  28.     }    
  29. }    
  30. catch (Exception Ex)    
  31. {    
  32.     Console.WriteLine(Ex.ToString());    
  33. }

Read and Write a File

Open a File

A File must be opened using an IO resource before it can be read or write to. A file can be opened to read and/or write purpose. The FileInfo class provides four methods to open a file.

  • Open
  • OpenRead
  • OpenText
  • OpenWrite

File.Open Method

The Open method opens a FileStream on the specified file in the specified file mode.

  1. FileStream fs = fi.Open(FileMode.Open, FileAccess.Write);

Here is the complete code sample.

  1. string fileName = @"C:\Temp\MaheshTXFITx.txt";    
  2. FileInfo fi = new FileInfo(fileName);    
  3. // If file does not exist, create file     
  4. if (!fi.Exists)    
  5. {    
  6.     //Create the file.      
  7.     using (FileStream fs = fi.Create())    
  8.     {    
  9.         Byte[] info = new UTF8Encoding(true).GetBytes("File Start");    
  10.         fs.Write(info, 0, info.Length);    
  11.     }    
  12. }    
  13. try    
  14. {    
  15.     using (FileStream fs = fi.Open(FileMode.Open, FileAccess.Write))    
  16.     {    
  17.         Byte[] info = new UTF8Encoding(true).GetBytes("Add more text");    
  18.         fs.Write(info, 0, info.Length);    
  19.     }    
  20. }    
  21. catch (Exception Ex)    
  22. {    
  23.     Console.WriteLine(Ex.ToString());    
  24. }

File.OpenRead Method

The OpenRead method opens a file for reading. The method returns a FileStream object that is used to read a file using its Read method.

  1. string fileName = @"C:\Temp\MaheshTXFITx.txt";    
  2. FileInfo fi = new FileInfo(fileName);   
  3. FileStream fs = fi.OpenRead();

The file is read into a byte array. The following code snippet uses the FileStream.Read method and gets text into a byte array and then it is converted to a string using UTF8Encoding.GetString method.

  1. using (FileStream fs = fi.OpenRead())    
  2. {    
  3.     byte[] byteArray = new byte[1024];    
  4.     UTF8Encoding fileContent = new UTF8Encoding(true);    
  5.     while (fs.Read(byteArray, 0, byteArray.Length) > 0)    
  6.     {    
  7.         Console.WriteLine(fileContent.GetString(byteArray));    
  8.     }    
  9. }

The following lists the complete code sample.

  1. string fileName = @"C:\Temp\MaheshTXFITx.txt";    
  2. FileInfo fi = new FileInfo(fileName);    
  3. // If file does not exist, create file     
  4. if (!fi.Exists)    
  5. {    
  6.     //Create the file.      
  7.     using (FileStream fs = fi.Create())    
  8.     {    
  9.         Byte[] info = new UTF8Encoding(true).GetBytes("File Start");    
  10.         fs.Write(info, 0, info.Length);    
  11.     
  12.     }    
  13. }    
  14. try    
  15. {    
  16.     
  17.     using (FileStream fs = fi.OpenRead())    
  18.     {    
  19.         byte[] byteArray = new byte[1024];    
  20.         UTF8Encoding fileContent = new UTF8Encoding(true);    
  21.         while (fs.Read(byteArray, 0, byteArray.Length) > 0)    
  22.         {    
  23.             Console.WriteLine(fileContent.GetString(byteArray));    
  24.         }    
  25.     }    
  26. }    
  27. catch (Exception Ex)    
  28. {    
  29.     Console.WriteLine(Ex.ToString());    
  30. }

File.OpenText Method

The OpenText method opens an existing UTF-8 encoded text file for reading. The OpenText method takes a file name as a parameter and returns a StreamReader object.

  1. StreamReader reader = fi.OpenText();

Once we have a StreamReader object, we can use its Read or ReadLine methods to read the contents. The ReadLine method reads one line at a time. The following code snippet loops through the entire content of a SteamReader and reads and prints one line at a time.

  1. while ((s = reader.ReadLine()) != null)    
  2. {    
  3.     Console.WriteLine(s);    
  4. }

The following lists the complete code sample.

  1. string fileName = @"C:\Temp\MaheshTXFITx.txt";    
  2. FileInfo fi = new FileInfo(fileName);    
  3. // If file does not exist, create file     
  4. if (!fi.Exists)    
  5. {    
  6.     //Create the file.      
  7.     using (FileStream fs = fi.Create())    
  8.     {    
  9.         Byte[] info = new UTF8Encoding(true).GetBytes("File Start");    
  10.         fs.Write(info, 0, info.Length);    
  11.     }    
  12. }    
  13. try    
  14. {    
  15.     using (StreamReader reader = fi.OpenText())    
  16.     {    
  17.         string s = "";    
  18.         while ((s = reader.ReadLine()) != null)    
  19.         {    
  20.             Console.WriteLine(s);    
  21.         }    
  22.     }    
  23. }    
  24. catch (Exception Ex)    
  25. {    
  26.     Console.WriteLine(Ex.ToString());    
  27. }

File.OpenWrite Method

The OpenWrite method opens a file for writing. If file does not exist, it creates a new file and opens if for writing. The OpenWrite method takes a file name as parameter and returns a FileStream object on the specified file.

  1. FileStream fs = fi.OpenWrite();

Once we have a FileStream object, we can use its Write method to write to the file. The WriteMethod takes a byte array. The following code snippet creates a byte array and passes it to the Write method of the FileStream.

  1. Byte[] info = new UTF8Encoding(true).GetBytes("New File using OpenWrite Method \n");    
  2. fs.Write(info, 0, info.Length);

The following lists the complete code sample.

  1. string fileName = @"C:\Temp\MaheshTXFITx.txt";    
  2. FileInfo fi = new FileInfo(fileName);    
  3. // If file does not exist, create file     
  4. if (!fi.Exists)    
  5. {    
  6.     //Create the file.      
  7.     using (FileStream fs = fi.Create())    
  8.     {    
  9.         Byte[] info = new UTF8Encoding(true).GetBytes("File Start");    
  10.         fs.Write(info, 0, info.Length);    
  11.     }    
  12. }    
  13. try    
  14. {    
  15.     // Open a file and add some contents to it       
  16.     using (FileStream fs = fi.OpenWrite())    
  17.     {    
  18.         Byte[] info = new UTF8Encoding(true).GetBytes("New File using OpenWrite Method\n");    
  19.         fs.Write(info, 0, info.Length);    
  20.         info = new UTF8Encoding(true).GetBytes("----------START------------------------\n");    
  21.         fs.Write(info, 0, info.Length);    
  22.         info = new UTF8Encoding(true).GetBytes("Author: Mahesh Chand \n");    
  23.         fs.Write(info, 0, info.Length);    
  24.         info = new UTF8Encoding(true).GetBytes("Book: ADO.NET Programming using C#\n");    
  25.         fs.Write(info, 0, info.Length);    
  26.         info = new UTF8Encoding(true).GetBytes("----------END------------------------");    
  27.         fs.Write(info, 0, info.Length);    
  28.     }    
  29.     // Read file contents and display on the console       
  30.     using (FileStream fs = File.OpenRead(fileName))    
  31.     {    
  32.         byte[] byteArray = new byte[1024];    
  33.         UTF8Encoding fileContent = new UTF8Encoding(true);    
  34.         while (fs.Read(byteArray, 0, byteArray.Length) > 0)    
  35.         {    
  36.             Console.WriteLine(fileContent.GetString(byteArray));    
  37.         }    
  38.     }    
  39. }    
  40. catch (Exception Ex)    
  41. {    
  42.     Console.WriteLine(Ex.ToString());    
  43. }

Append a File

The AppendText method creates a StreamWriter object that appends UTF-8 encoded text to an existing text file.

  1. string fileName = @"C:\Temp\Data\MaheshTXMoved.txt";     
  2. FileInfo fi = new FileInfo(fileName);      
  3. using (StreamWriter sw = fi.AppendText())      
  4. {      
  5.     sw.WriteLine("--------- Append Text Start ----------");      
  6.     sw.WriteLine("New author started");     
  7.     sw.WriteLine("a book on Files Programming ");     
  8.     sw.WriteLine("using C#");      
  9.     sw.WriteLine("--------- Append Text End ----------");      
  10. }      
  11. // Read all text      
  12. string readText = File.ReadAllText(fileName);     
  13. Console.WriteLine(readText);

Copy a File in C#

The Copy method copies an existing file to a new file on the specified location. The Copy method takes two parameters. First the file name to be copied to with full and the second parameter that is optional that is used to overwrite an existing file. If the second parameter is true, the Copy method will overwrite if file already exists.

The following code snippet copies a file to the destination file.

  1. string fileName = @"C:\Temp\MaheshTXFITx.txt";     
  2. FileInfo fi = new FileInfo(fileName);      
  3. string destinationFile = @"C:\Temp\Data\MaheshTXCopied.txt";      
  4. try      
  5. {      
  6.     fi.CopyTo(destinationFile, true);      
  7. }      
  8. catch (IOException iox)      
  9. {      
  10.     Console.WriteLine(iox.Message);      
  11. }

Move a File in C#

The Move method moves an existing file to a new location with the same or a different file name. The Move method takes the full path of the move file. The Move method deletes the original file.

The following code snippet moves the source file to the destination file.

  1. string fileName = @"C:\Temp\MaheshTXFITx.txt";     
  2. FileInfo fi = new FileInfo(fileName);      
  3. string destinationFile = @"C:\Temp\Data\MaheshTXMoved.txt";      
  4. try      
  5. {      
  6.     fi.MoveTo(destinationFile);      
  7. }      
  8. catch (IOException iox)      
  9. {      
  10.     Console.WriteLine(iox.Message);      
  11. }

Replace a File in C#

The Replace method replaces the contents of a specified file with the contents of another file. This method deletes the original file and creates a backup of the replaced file.

The following code snippet moves the contents of the original file into the replaced file and also creates a backup of the replaced file and deletes the original file.

  1. string repFile = @"C:\Temp\MaheshTXFI.txt";      
  2. string backupFile = @"C:\Temp\MaheshTXFI.txt.bac";     
  3. string fileName = @"C:\Temp\MaheshTXFITx.txt";     
  4. FileInfo fi = new FileInfo(fileName);      
  5. try      
  6. {      
  7.     fi.Replace(repFile, backupFile, false);      
  8. }      
  9. catch (IOException iox)      
  10. {      
  11.     Console.WriteLine(iox.Message);      
  12. }

Delete a File in C#

The Delete method deletes the specified file permanently. The following code snippet deletes a file.

  1. string fileName = @"C:\Temp\Data\MaheshTXMoved.txt";     
  2. FileInfo fi = new FileInfo(fileName);      
  3. try      
  4. {      
  5.     fi.Delete();      
  6. }      
  7. catch (IOException iox)      
  8. {      
  9.     Console.WriteLine(iox.Message);      
  10. }

Encrypt a File in C#

The Encrypt method encrypts a file so that only the account used to encrypt the file can decrypt it.

  1. string fileName = @"C:\Temp\Data\MaheshTXMoved.txt";    
  2. FileInfo fi = new FileInfo(fileName);    
  3. fi.Encrypt();    
  4. fi.Decrypt();

Decrypt a File in C#

The Decrypt method decrypts an encrypted file. Only account that has encrypted a file can decrypt a file.

  1. string fileName = @"C:\Temp\Data\MaheshTXMoved.txt";    
  2. FileInfo fi = new FileInfo(fileName);    
  3. fi.Encrypt();    
  4. fi.Decrypt();

Summary

In this tutorial, we learned how to use C# FileInfo class, its methods, and properties to work with files including file creation, file editing, deleting files, moving files, and ecryptying and decrypting files.