There are multiple ways you can create files in C# and FileInfo class is one of them. The FileInfo class in the .NET Framework class library provides static methods for creating, reading, copying, moving, and deleting files using the FileStream objects.
The FileInfo class is defined in the System.IO namespace. You must import this namespace before using the class.
A FileInfo object is created using the default constructor that takes a string as a file name with a full path.
- string fileName = @"C:\Temp\MaheshTXFI.txt";
- FileInfo fi = new FileInfo(fileName);
Sample
Here is a complete sample that not only creates a file but also reads a file attributes such as file creation time, its size, last updated, last accessed, and last write times.
-
- string fileName = @"C:\Temp\MaheshTXFI.txt";
- FileInfo fi = new FileInfo(fileName);
-
-
- using (FileStream fs = fi.Create())
- {
- Byte[] txt = new UTF8Encoding(true).GetBytes("New file.");
- fs.Write(txt, 0, txt.Length);
- Byte[] author = new UTF8Encoding(true).GetBytes("Author Mahesh Chand");
- fs.Write(author, 0, author.Length);
- }
-
-
- string justFileName = fi.Name;
- Console.WriteLine("File Name: {0}", justFileName);
-
- string fullFileName = fi.FullName;
- Console.WriteLine("File Name: {0}", fullFileName);
-
- string extn = fi.Extension;
- Console.WriteLine("File Extension: {0}", extn);
-
- string directoryName = fi.DirectoryName;
- Console.WriteLine("Directory Name: {0}", directoryName);
-
- bool exists = fi.Exists;
- Console.WriteLine("File Exists: {0}", exists);
- if (fi.Exists)
- {
-
- long size = fi.Length;
- Console.WriteLine("File Size in Bytes: {0}", size);
-
- bool IsReadOnly = fi.IsReadOnly;
- Console.WriteLine("Is ReadOnly: {0}", IsReadOnly);
-
- DateTime creationTime = fi.CreationTime;
- Console.WriteLine("Creation time: {0}", creationTime);
- DateTime accessTime = fi.LastAccessTime;
- Console.WriteLine("Last access time: {0}", accessTime);
- DateTime updatedTime = fi.LastWriteTime;
- Console.WriteLine("Last write time: {0}", updatedTime);
- }
Here is a detailed tutorial:
Working with FileInfo Class in C#