📌  相关文章
📜  C#FileInfo(1)

📅  最后修改于: 2023-12-03 15:00:14.307000             🧑  作者: Mango

C# FileInfo

The FileInfo class in C# provides you with the ability to retrieve information associated with a file. It is a part of the System.IO namespace, which is responsible for manipulating files and folders.

Creating a FileInfo object

To work with a file using the FileInfo class, you first need to create a FileInfo object that points to the file. You can create a FileInfo object by specifying the file path.

FileInfo fileInfo = new FileInfo("C:\\test\\example.txt");

You can also use the Path class to create a path string and then use it to create a FileInfo object.

string filePath = Path.Combine(@"C:\test", "example.txt");
FileInfo fileInfo = new FileInfo(filePath);
Retrieving file information

Once you have created a FileInfo object, you can use it to retrieve information associated with the file. Some of the commonly used properties and methods are:

  • Name: Gets the name of the file, including its extension.
  • DirectoryName: Gets the full path of the directory that contains the file.
  • FullName: Gets the full path of the file.
  • Exists: Returns true if the file exists, otherwise false.
  • Attributes: Gets or sets the attributes of the file (Archive, Hidden, ReadOnly, System, Normal).
  • Length: Gets the size of the file in bytes.
  • CreationTime: Gets or sets the time the file was created.
  • LastAccessTime: Gets or sets the time the file was last accessed.
  • LastWriteTime: Gets or sets the time the file was last written to.
Console.WriteLine($"Name: {fileInfo.Name}");
Console.WriteLine($"Directory: {fileInfo.DirectoryName}");
Console.WriteLine($"Full path: {fileInfo.FullName}");
Console.WriteLine($"Exists: {fileInfo.Exists}");
Console.WriteLine($"Size: {fileInfo.Length} bytes");
Console.WriteLine($"Created: {fileInfo.CreationTime}");
Console.WriteLine($"Last accessed: {fileInfo.LastAccessTime}");
Console.WriteLine($"Last written to: {fileInfo.LastWriteTime}");
Modifying file attributes

You can also modify the attributes of the file using the Attributes property. For example, to set the file as read-only, use the following code:

fileInfo.Attributes |= FileAttributes.ReadOnly;

Similarly, to unset the read-only attribute:

fileInfo.Attributes &= ~FileAttributes.ReadOnly;
Conclusion

The FileInfo class is a powerful tool for manipulating files in C#. By using it to retrieve file information, you can gain valuable insights into the files you are working with and make more informed decisions. By modifying file attributes, you can also exert greater control over your file system.