C# FileInfo Examples

FileInfo gets file statistics. It retrieves information about a specific file or directory from the file system in a C# program. The FileInfo type provides a host of methods and properties that helps you detect the status of the file.

FileInfo type

Attributes

Every file on the Windows File system stores a set of attributes that tell you certain things about the file. You can detect its visibility, whether it is a directory, and if it is read-only. The Attributes property returns an enumerated constant that is encoded as enum flags; you can test these flags individually.

Enum Flags Attribute
Program that uses Attributes [C#]

using System;
using System.IO;

class Program
{
    static void Main()
    {
	// Get Attributes for file.
	FileInfo info = new FileInfo("C:\\file.txt");
	FileAttributes attributes = info.Attributes;
	Console.WriteLine(attributes);

	// Get Attributes for directory.
	info = new FileInfo("C:\\");
	attributes = info.Attributes;
	Console.WriteLine(attributes);
    }
}

Output

Archive
Hidden, System, Directory

Possible values for FileAttributes. There are many different flags on the FileAttributes enum. Some of them, such as ReadOnly, can be retrieved in other ways.

Examples

FileAttributes.Archive
FileAttributes.Compressed
FileAttributes.Device
FileAttributes.Directory
FileAttributes.Encrypted
FileAttributes.Hidden
FileAttributes.Normal
FileAttributes.NotContentIndexed
FileAttributes.Offline
FileAttributes.ReadOnly
FileAttributes.ReparsePoint
FileAttributes.SparseFile
FileAttributes.System
FileAttributes.Temporary

ReadOnly and IsReadOnly method. If you are trying to determine if a file is read-only, you can use the IsReadOnly method instead of the FileAttributes.ReadOnly constant. This may result in easier-to-understand code.

Times

The Windows file system keeps track of a file's creation time, its last access, and its last write time. You can access this information with the FileInfo type and the CreationTime, LastAccessTime and LastWriteTime properties.

File.GetLastWriteTimeUtc Example
Program that uses Time properties [C#]

using System;
using System.IO;

class Program
{
    static void Main()
    {
	FileInfo info = new FileInfo("C:\\file.txt");

	DateTime time = info.CreationTime;
	Console.WriteLine(time);

	time = info.LastAccessTime;
	Console.WriteLine(time);

	time = info.LastWriteTime;
	Console.WriteLine(time);
    }
}

Output

7/17/2010 9:48:48 AM
7/17/2010 9:48:48 AM
8/18/2010 4:48:27 PM

Utc time methods. You can also get the creation, last access, and last write times in Coordinated Universal Time. This is ideal if you want to store the times and compare them to times on other computers that are located elsewhere.

Directory

Every file on the file system is stored in a containing directory. You can quickly access this DirectoryInfo with the Directory property. Alternatively, you can get just the name of the directory with the DirectoryName string property.

Program that uses Directory property [C#]

using System;
using System.IO;

class Program
{
    static void Main()
    {
	// Get file info.
	FileInfo info = new FileInfo("C:\\file.txt");

	// Access parent directory.
	DirectoryInfo dir = info.Directory;
	Console.WriteLine(dir.Name);

	// Get directory name.
	string name = info.DirectoryName;
	Console.WriteLine(name);
    }
}

Output

C:\
C:\

Exists

You can create a FileInfo for a file that does not exist; no exception will be thrown. To see if the file does not exist, you can test the result of the Exists property. This has the same result as the File.Exists method.

File.Exists Method
Program that uses Exists property [C#]

using System;
using System.IO;

class Program
{
    static void Main()
    {
	// Get file info.
	FileInfo info = new FileInfo("C:\\does-not-exist.txt");
	bool exists = info.Exists;
	Console.WriteLine(exists);
    }
}

Output

False

Name and Extension

Typically, you should use the Path type to get file name parts such as the name or extension. However, the FileInfo type provides ways to get some of these parts as well: you can get the Name, which doesn't include the directory; the FullName; or the Extension, which includes the period.

Path Examples
Program that uses file name properties [C#]

using System;
using System.IO;

class Program
{
    static void Main()
    {
	// Get file info.
	FileInfo info = new FileInfo("C:\\file.txt");

	string name = info.Name;
	string fullName = info.FullName;
	string extension = info.Extension; // Has period

	Console.WriteLine(name);
	Console.WriteLine(fullName);
	Console.WriteLine(extension);
    }
}

Output

file.txt
C:\file.txt
.txt

Length

Question and answer

How many bytes are in your file? The Length property on the FileInfo type provides a way for you to effectively determine this. This figure is in bytes, not megabytes or kilobytes, so if you want to display it as megabytes you will need to convert it first.

FileInfo Length, Get File Size Sort Files by Their Sizes Get Directory Size Convert Bytes to Megabytes
Program that uses Length property [C#]

using System;
using System.IO;

class Program
{
    static void Main()
    {
	FileInfo info = new FileInfo("C:\\a");
	long value = info.Length;
	Console.WriteLine(value);
    }
}

Output

5320683

MoveTo

You can you the FileInfo type to rename (move) a file. This should reduce copying in the file system over creating a duplicate file and deleting the original.

FileInfo MoveTo Method

CopyTo and Replace. The CopyTo and Replace methods provide parallel functionality to the MoveTo method. Instead of renaming, CopyTo simply makes a copy of the file. The Replace method allows you to copy a file to an existing location and also make a backup file.

Text methods

If your FileInfo points to a text file, it is a good idea to use the AppendText, CreateText, and OpenText methods to acquire a StreamWriter or StreamReader instance. You should wrap these in the using-resource-acquisition statement. This example demonstrates this syntax form.

Using StreamWriter Using StreamReader
Program that uses text properties [C#]

using System;
using System.IO;

class Program
{
    static void Main()
    {
	// This file will have a new line at the end.
	FileInfo info = new FileInfo("C:\\file.txt");
	using (StreamWriter writer = info.AppendText())
	{
	    writer.WriteLine("Line");
	}

	// This file will have the word New in it.
	info = new FileInfo("C:\\new.txt");
	using (StreamWriter writer = info.CreateText())
	{
	    writer.WriteLine("New");
	}

	// Get a StreamReader with OpenText.
	using (StreamReader reader = info.OpenText())
	{
	    Console.WriteLine(reader.ReadToEnd());
	}
    }
}

Output

New

FileStream methods

Stream abstract type

Sometimes, you are dealing with a non-text file and want to use types such as BinaryReader or BinaryWriter on a file. To do this from a FileInfo instance, use the Create and Open methods, and then create the BinaryReader from the FileStream.

BinaryReader Tutorial BinaryWriter Tutorial

Create [returns FileStream]
Open [returns FileStream]

Security

The C# programming language

The FileInfo type provides a way to retrieve and store security information on the file system. This is most important for multi-user servers that have restricted information. These methods are not covered in detail here.

GetAccessControl
SetAccessControl

GetLifetimeService
InitializeLifetimeService

Encrypt and Decrypt

The Encrypt and Decrypt methods are not available on all Windows computers. If you choose to use them, you can wrap them in exception-handling in the chance that the computer does not support them.

Error caused by using Encrypt when unsupported

Unhandled Exception: System.IO.IOException: The request is not supported.

   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   at System.IO.File.Encrypt(String path)
   at System.IO.FileInfo.Encrypt()
   at Program.Main() in C:\...Program.cs:line 10

Remoting

.NET Framework information

Although we don't cover it here, the Remoting capability in the .NET Framework provides support for the FileInfo type. You can use the CreateObjectRef methods to enable remoting on a FileInfo instance.

Summary

By providing these properties and methods, the FileInfo type makes it easy to get information from the file system about a file. You can use this information to make important branches in your program's logic.

File Handling
.NET