Curriculum
FileInfo is a class in C# that provides information about a file and allows you to perform operations on the file, such as reading or writing its contents. Here’s an example of using FileInfo to read the contents of a text file:
using System;
using System.IO;
class Program
{
static void Main(string[] args)
{
// Create a FileInfo object for the file we want to read
FileInfo fileInfo = new FileInfo("test.txt");
// Check if the file exists
if (!fileInfo.Exists)
{
Console.WriteLine("File not found!");
return;
}
// Open the file and create a StreamReader to read its contents
using (FileStream fileStream = fileInfo.OpenRead())
using (StreamReader streamReader = new StreamReader(fileStream))
{
// Read the contents of the file
string fileContents = streamReader.ReadToEnd();
// Display the contents of the file
Console.WriteLine(fileContents);
}
}
}
In this example, we first create a FileInfo object for the file we want to read. We then check if the file exists by calling the Exists property of the FileInfo object. If the file does not exist, we display an error message and return from the method.
Next, we open the file using the OpenRead method of the FileInfo object, which returns a FileStream object that represents the file. We then create a StreamReader object to read the contents of the file.
We use the ReadToEnd method of the StreamReader object to read the entire contents of the file into a string variable named fileContents. Finally, we display the contents of the file by calling the Console.WriteLine method.
It’s important to note that FileInfo provides many other useful properties and methods for working with files, such as Delete to delete a file, CopyTo to copy a file to another location, Length to get the size of the file, and LastWriteTime to get the last time the file was modified.