C# FileInfo Class: All You Could Possibly Need to Know about a File

c# fileinfoC# is designed specifically to be a platform independent language. Its syntax resembles that of the C and C++ programming languages. It does not support multiple inheritance, instead it provides interfaces. Through interfaces, several classes can implement the same set of methods. A major feature of C# is garbage collection. Also C# provides direct access to memory through C++ style pointers.

However, remember that these pointers are not garbage collected till they are specifically released by the programmer. C# programs are compiled to Microsoft Intermediate Language(MSIL) which is a language like Java’s byte code. This way, C# can be platform independent and execute using just in time compiling. Today we walk you through the C# FileInfo class, which is an important class to do file operations. This requires that you have a basic knowledge of C#, so you may want to first take this beginners course on C#.

What is FileInfo Class?

FileInfo obtains file statistics. It provides a number of methods and properties in order to detect the status of the file. Every file has a set of attributes which give you information about the file. The parent class of the FileInfo class is the FileSystemInfo class. FileInfo class possess properties and methods to  create, copy  delete, move and open files. It also helps in the creation of FileStream objects. Note that this class cannot be inherited. The syntax of FileInfo class looks like this

public sealed class FileInfo : FileSystemInfo

Here is a list of the commonly used properties of FileInfo class.

  • Attributes –  Returns the attributes of the current file.
  • Creation Time – Returns the time of when the file was created.
  • Directory – Extracts the directory to which the file belongs.
  • Exists – Returns a Boolean value which indicates whether the file exists.
  • Extension – Returns the file extension which is represented by a string.
  • FullName – Returns the full path of the file.
  • LastAccessTime – Returns the time when the file was last accessed.
  • LastWriteTime – Returns the time when the file was last modified.
  • Length- Returns the exact size in bytes of the file.
  • Name – Returns the name of the file.

Methods of FileInfo Class

Let’s take a look at some of the commonly used methods of the FileInfo class.

  • public StreamWriter AppendText()-This method results in creation of a StreamWriter which appends text to the file.
  • public FileStream Create()-This methods is used to create a new file.
  • public override void Delete()-If you want to delete a file permanently use this method.
  • public void MoveTo( string destFileName )- This method is used in order to move a file to a new location. You have the option to specify a new name for the file.
  • public FileStream Open( FileMode mode )- If you want to open a file in a specified mode, this method is used.
  • public FileStream Open( FileMode mode, FileAccess access ) – This method is used to open a file in a specified mode which has read, write or read/write access.
  • public FileStream Open( FileMode mode, FileAccess access, FileShare share ) – This is similar to the above method with the addition of the specified sharing option.
  • public FileStream OpenRead()- You can use this method if you want to create read only FileStream.
  • public FileStream OpenWrite()- This method is used to create a write only FileStream.

Next, let’s walk through some examples of FileInfo Class. These are simple programs which will help you understand how to use the FileInfo class in C# programs. To learn more about FileInfo, feel free to look up this tutorial on C#.

Example 1- Program to Display the Attributes of the Input File

using System;
using System.IO;
class Example1
{
static void Main()
{
FileInfo info1 = new FileInfo("C:\\hello.txt");
FileAttributes attributes1 = info1.Attributes;
Console.WriteLine(attributes1);
info2 = new FileInfo("C:\\");
attributes2 = info2.Attributes;
Console.WriteLine(attributes2);
}
}

In this program, we first create a new file passing its path and name as parameters to the FileInfo class. Then we get the attributes of the newly created file. We use the Console.WriteLine() function to display the attributes on the screen. Next, we create a new directory, using this class. We get its attributes and display them on the screen. To explore some more options, you can take this course on C#.

Example 2- Program to Find Out the Time of Creation, Modification and Last Access of the Input File

using System;
using System.IO;
class Example2
{
static void Main()
{
FileInfo info1 = new FileInfo("C:\\hello.txt");
DateTime time = info1.CreationTime;
Console.WriteLine(time);
time = info1.LastAccessTime;
Console.WriteLine(time);
time = info1.LastWriteTime;
Console.WriteLine(time);
}
}

In this program, we create a new file using the FileInfo Class. We declare the time variable to be of type DateTime. Then we extract the time when the file was first created, the last access time and the last time the when the file was modified. After that we just display these times on the screen. You can learn more about various display options in C# with this course.

 Example 3-Program that Uses Directory Property

 using System;
using System.IO;
class Program
{
static void Main()
{
FileInfo info_new = new FileInfo("C:\\Hello.txt");
DirectoryInfo dir = info_new.Directory;
Console.WriteLine(dir.Name);
string name = info_new.DirectoryName;
Console.WriteLine(name);
}
}

Every file is stored in a particular directory. You can use either the directory property or directory name string property to get the name of the directory.

Example 4 – Program that Uses Exists Property

using System;
using System.IO;
class Example
{
static void Main()
{
FileInfo info1 = new FileInfo("C:\\does-not-exist.txt");
bool exists = info1.Exists;
Console.WriteLine(exists);
}
}

In this program, you can create a FileInfo object for a file that does not exist. Note that no exceptions will be thrown in this case. You can use the Exists property of the FileInfo to test if the file does not exist.

Example 5 – Program that Uses File Name Properties

 using System;
using System.IO;
class Example
{
static void Main()
{
FileInfo info_new = new FileInfo("C:\\Hello.txt");
string name = info_new.Name;
string fullName = info_new.FullName;
string extension = info_new.Extension;
Console.WriteLine(name);
Console.WriteLine(fullName);
Console.WriteLine(extension);
}
}

In this program, we use the properties of the FileInfo type to get the name of the file, the full path of the file and the file extension.

Example 6 – Program that Uses Length Property

using System;
using System.IO;
 class Example
{
static void Main()
{
FileInfo info_new = new FileInfo("C:\\Hello.txt");
long value = info_new.Length;
Console.WriteLine(value);
}
}

In this program, we use the Length property of the FileInfo type to return the length of the file in bytes.

Example 7 – Program that Uses Text Properties

using System;
using System.IO;
class Example
{
static void Main()
{
FileInfo info_new = new FileInfo("C:\\Hello.txt");
using (StreamWriter writer = info_new.AppendText())
{
writer.WriteLine("Line");
}
Info_new = new FileInfo("C:\\new.txt");
using (StreamWriter writer = info_new.CreateText())
{
writer.WriteLine("New");
}
using (StreamReader reader = info_new.OpenText())
{
Console.WriteLine(reader.ReadToEnd());
}
}
}

AppendText method creates a StreamWriter object that appends text to the file.  CreateText Method creates a StreamWriter object that writes a new file. OpenText method creates a StreamReader object with UTF8 encoding that reads from a text file.

Example 8 – Program that Uses MoveTo Method

using System.IO;
class Example
{
static void Main()
{
File.WriteAllText("C:\\Hello1.txt", "X");
FileInfo info_new = new FileInfo("C:\\Hello1.txt");
info_new.MoveTo("C:\\Hello2.txt");
}
}

FileInfo has the capability to rename a file. The MoveTo method is used to do this. This method tells OS to rename the file. This method is more efficient compared to using multiple file operations. We write some text in the specified file using the WriteAllText method.Then we create a FileInfo instance for the specified path. Finally, we invoke the MoveTo instance method to change the location of the file.

Hope this article was fun and interesting. Experiment with the code giving it your own inputs. Creating your own programs is the best way to learn the concepts. Once you’re ready to move on to the next step, you can try creating your own Android Apps in C#, with this course.