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