File class can be used for various operations such as creating a new file, appending to an existing file or opening a file in different mode or access state. File class can be used for getting information e.g. when a file was created, accessed or modified.
However, information like what is the name of the file, its file extension etc. cannot be derived using File class. For file information, .NET provides FileInfo class.
FileInfo is a non-static sealed class which inherits FileSystemInfo class abstract class. The FileSystemInfo class provides several properties such as:
public string? LinkTarget { get; }
public DateTime LastWriteTimeUtc { get; set; }
public DateTime LastWriteTime { get; set; }
public DateTime LastAccessTimeUtc { get; set; }
public DateTime LastAccessTime { get; set; }
public virtual string FullName { get; }
public string Extension { get; }
public abstract bool Exists { get; }
public DateTime CreationTime { get; set; }
public abstract string Name { get; }
public FileAttributes Attributes { get; set; }
public DateTime CreationTimeUtc { get; set; }
public UnixFileMode UnixFileMode { get; set; }
Needless to say that these properties are inherited by FileInfo class. The FileInfo class provides following other properties:
public bool IsReadOnly { get; set; }
public string? DirectoryName { get; }
public DirectoryInfo? Directory { get; }
public long Length { get; }
The FileInfo class provides methods to create, copy, move, rename, encrypt, decrypt or open a file.
Note that fileInfo.Create(path) returns FileStream but fileInfo.CreateText(path) returns StreamWriter. FileStream is more versatile than StreamWriter e.g. FileStream can read/write both.
- fileInfo.Create(path) returns FileStream.
- fileInfo.CreateText(path) returns StreamWriter.
Example1. Create a list of 10 files in target directory. Each file name should suffix with a number, increasing from the previous one. (e.g. file1, file2 etc.).
class Demo
{
static void Main()
{
string desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string folder = Path.Combine(desktop, "files");
for (int i = 1; i < 11; i++)
{
using (StreamWriter writer = new FileInfo(Path.Combine(folder, "sample" + i + ".csv")).CreateText())
{
writer.WriteLine("This is a sample file no. " + i);
}
}
}
}
Example2. List all files of a folder with their full path
class Demo
{
static void Main()
{
string desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string folder = Path.Combine(desktop, "files");
if (Directory.Exists(folder))
{
string[] files = Directory.GetFiles(folder);
if (files.Length > 0)
{
foreach (var file in files)
{
Console.WriteLine(file);
}
}
}
}
}
/*
C:\Users\ajeet\Desktop\files\Confessions Jean J Rausso.txt
C:\Users\ajeet\Desktop\files\create.txt
C:\Users\ajeet\Desktop\files\create1.txt
*/
Example3. List all files of a folder with their short name
class Demo
{
static void Main()
{
string desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string folder = Path.Combine(desktop, "files");
if (Directory.Exists(folder))
{
string[] files = Directory.GetFiles(folder);
if (files.Length > 0)
{
foreach (var file in files)
{
Console.WriteLine(new FileInfo(file).Name);
}
}
}
}
}
/*
Confessions Jean J Rausso.txt
create.txt
create1.txt
*/
Tips. Use LINQ for concise code:
class Demo
{
static void Main()
{
string desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string folder = Path.Combine(desktop, "files");
if (Directory.Exists(folder))
{
string[] files = Directory.GetFiles(folder);
if (files.Length > 0)
{
files.ToList().ForEach(file => Console.WriteLine(file));
}
}
}
}
Example4. List Distinct file extensions of all files of a folder
using System.Text;
class Demo
{
static void Main()
{
string desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string folder = Path.Combine(desktop, "files");
if (Directory.Exists(folder))
{
string[] files = Directory.GetFiles(folder);
if (files.Length > 0)
{
StringBuilder sb = new StringBuilder();
foreach (var file in files)
{
sb.Append(new FileInfo(file).Extension + "|");
}
string[] allExtensions = sb.ToString().Split(new char[] { '|' });
allExtensions.Distinct<string>().ToList().ForEach(x => Console.Write(x + " "));
//IEnumerable<string> extns = allExtensions.Distinct<string>();
//foreach (string ext in extns)
//{
// Console.WriteLine(ext);
//}
}
}
}
}
Alternative Better Solution: For extension extraction only, Path.GetExtension() is the most direct choice.
class Demo
{
static void Main()
{
string desktop = Environment.GetFolderPath(
Environment.SpecialFolder.Desktop);
string folder = Path.Combine(desktop, "files");
if (Directory.Exists(folder))
{
Directory.GetFiles(folder)
.Select(Path.GetExtension)
.Distinct()
.ToList()
.ForEach(ext => Console.Write(ext + " "));
}
}
}
Example5. List properties of all files of a folder
class Demo
{
static void Main()
{
string desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string folder = Path.Combine(desktop, "myfolder");
string[] files = Directory.GetFiles(folder);
foreach (string file in files)
{
FileInfo fileInfo = new FileInfo(file);
Console.WriteLine($"Name: {fileInfo.Name}");
Console.WriteLine($"Size: {fileInfo.Length} bytes");
Console.WriteLine($"Created: {fileInfo.CreationTime}");
Console.WriteLine($"Last Access Time: {fileInfo.LastAccessTime}");
Console.WriteLine($"Directory Name: {fileInfo.DirectoryName}");
Console.WriteLine();
}
}
}