There are multiple ways you can create files in C# and FileInfo class is one of them. The FileInfo class in the .NET Framework class library provides static methods for creating, reading, copying, moving, and deleting files using the FileStream objects.

The FileInfo class is defined in the System.IO namespace. You must import this namespace before using the class.

  1. using System.IO;

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);
Sample

Here is a complete sample that not only creates a file but also reads a file attributes such as file creation time, its size, last updated, last accessed, and last write times.

  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. }
Here is a detailed tutorial: Working with FileInfo Class in C#