c-sharp
  1. c-sharp-fileinfo

C# FileInfo

The FileInfo class in C# provides file information such as the file name, extension, size, and others. It can be used to interact with files on a local machine. In this tutorial, we'll discuss how to use the FileInfo class to manage files.

Syntax

To use the FileInfo class in C#, you need to create an instance of the class and then execute its methods. Here's how to create an instance of the FileInfo class:

FileInfo fileInfo = new FileInfo("path_to_file");

After creating an instance, you can use its properties and methods to get file information.

Example

Let's say we want to get information about a file called "example.txt". Here's an example of how we can use the FileInfo class to get its information:

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

Console.WriteLine("File name: " + fileInfo.Name);
Console.WriteLine("File path: " + fileInfo.FullName);
Console.WriteLine("File size: " + fileInfo.Length + " bytes");
Console.WriteLine("File extension: " + fileInfo.Extension);

Output

When we run the example code above, the output will be:

File name: example.txt
File path: C:\Files\example.txt
File size: 1024 bytes
File extension: .txt

This is because we created an instance of the FileInfo class for the file "example.txt", and then used its properties to get information such as the file name, path, size, and extension.

Explanation

In the example above, we created an instance of the FileInfo class for a file called "example.txt" located on the C: drive in the "Files" directory. We then used its Name, FullName, Length, and Extension properties to get information about the file, such as the file name, path, size, and extension. The properties are self-explanatory and provide useful data for working with files.

Use

The FileInfo class can be used to get information about a file, such as its name, path, size, and extension. It can also be used to create, copy, delete, and move files, as well as to read or write to them.

Important Points

  • Make sure to use the correct file path when creating an instance of the FileInfo class, otherwise, you'll get a runtime error.
  • You can use the static Directory.Exists() and File.Exists() methods to check if a directory or file exists, respectively, before creating a FileInfo instance.
  • The FileInfo class provides methods for creating, copying, moving, and deleting files (e.g. Create(), CopyTo(), MoveTo(), Delete()).

Summary

In this tutorial, we discussed how to use the FileInfo class in C# to get information about a file. We covered the syntax, example, output, explanation, use, and important points of the FileInfo class in C#. With this knowledge, you can now use the FileInfo class in your C# code to interact with files and get information about them.

Published on: