How to check if a file exists in C#

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



Mindcracker
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.