Home
Search
C# FileInfo ExamplesUse the FileInfo type from System.IO to get attributes, times, and names from files.
dot net perls
FileInfo. This type gets information about a file. It retrieves information about a specific file or directory from the file system.
Type details. The FileInfo type provides many methods and properties. These help us detect the status of a file. We can get Length or dates.
File
FileInfo Length
Attributes. Every file on the Windows File system stores a set of attributes. You can detect its visibility, whether it is a directory, and if it is read-only.
Note The Attributes property returns an enumerated constant that is encoded as enum flags. You can individually test these flags.
Enum Flags
C# program that uses Attributes
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); } }
Archive Hidden, System, Directory
Values, FileAttributes. There are many different flags on the FileAttributes enum. Some of them, such as ReadOnly, can be retrieved in other ways. This is true for many .NET methods.
FileAttributes values:
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
Times. The Windows file system keeps track of a file's creation time, its last access, and its last write time. We can get this information with the FileInfo type.
Here We access the CreationTime, LastAccessTime and LastWriteTime properties. The program prints these values.
Console
Utc time You can also get the creation, last access, and last write times in Coordinated Universal Time.
C# program that uses Time properties
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); } }
7/17/2010 9:48:48 AM 7/17/2010 9:48:48 AM 8/18/2010 4:48:27 PM
Directory. Every file on the file system is stored in a containing directory. You can quickly access this DirectoryInfo with the Directory property.
Info Alternatively, you can get just the name of the directory with the DirectoryName string property.
Directory
C# program that uses Directory property
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); } }
C:\ C:\
Exists. You can create a FileInfo for a file that does not exist. To see if the file does not exist, you can test the result of the Exists property. It is true or false.
Bool
File.Exists
C# program that uses Exists property
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); } }
False
Name, extension. Typically, you should use the Path type to get file name parts such as the name or extension. But the FileInfo type provides ways to get some of these parts as well.
Path
C# program that uses file name properties
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); } }
file.txt C:\file.txt .txt
Length. How many bytes are in a file? The Length property on the FileInfo type provides a way to effectively determine this. It returns a figure in bytes.
Sort Files, Sizes
Directory Size
Convert Bytes, Megabytes
C# program that uses Length property
using System; using System.IO; class Program { static void Main() { FileInfo info = new FileInfo("C:\\a"); long value = info.Length; Console.WriteLine(value); } }
5320683
MoveTo. You can use 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.
Also CopyTo and Replace provide parallel functionality to the MoveTo method. Instead of renaming, CopyTo makes a copy of the file.
And The Replace method allows you to copy a file to an existing location and also make a backup file.
C# program that uses MoveTo method on FileInfo
using System.IO; class Program { static void Main() { // Write the specified file with some text. File.WriteAllText("C:\\test1.txt", "A"); // Create a FileInfo instance for the specified path. // ... Then move the specified file to a new file path. FileInfo info = new FileInfo("C:\\test1.txt"); info.MoveTo("C:\\test2.txt"); } }
1. One file is created. 2. The file is renamed to a new name.
Text. 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.
Using You should wrap these in the using-resource-acquisition statement. This improves resource usage.
Using
Tip Directly creating a StreamWriter or Reader is a simpler pattern, one more common, and it should be preferred.
StreamWriter
StreamReader
C# program that uses text properties
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()); } } }
New
Security. 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.
Security methods
GetAccessControl SetAccessControl GetLifetimeService InitializeLifetimeService
Encrypt. 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.
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
ReadOnly, IsReadOnly. If you are trying to determine if a file is read-only, you can use the IsReadOnly method instead of the FileAttributes.ReadOnly constant.
FileStream. Sometimes, we deal with a non-text file and want to use types such as BinaryReader or BinaryWriter on a file. This is possible with a FileStream.
BinaryReader
BinaryWriter
A summary. By providing these properties and methods, the FileInfo type makes it easy to get information from the file system about a file.
Home
© 2007-2021 sam allen. see site info on the changelog