Working with FileInfo and DirectoryInfo in C# WinForms

Inspect, manage, and navigate the file system in your WinForms apps

When your app needs to inspect files, check sizes, list folders, or handle metadata, System.IO.FileInfo and System.IO.DirectoryInfo give you a powerful, object-oriented way to interact with the filesystem.

Let’s explore how to use them effectively in WinForms.


🧰 What Are FileInfo and DirectoryInfo?

They are C# classes that wrap file/folder metadata and actions in easy-to-use objects.

βœ… FileInfo lets you:

  • Check size, creation time, last modified time
  • Copy, delete, or move files
  • Get file extension, path, or name

βœ… DirectoryInfo lets you:

  • List all files or folders in a directory
  • Create or delete folders
  • Get folder details like size, contents, subfolders

πŸ“„ Example: Get Info About a File

private void btnInspectFile_Click(object sender, EventArgs e)
{
    string filePath = @"C:\Users\Public\Documents\example.txt";

    FileInfo fileInfo = new FileInfo(filePath);

    if (fileInfo.Exists)
    {
        string info = $"Name: {fileInfo.Name}\n" +
                      $"Size: {fileInfo.Length} bytes\n" +
                      $"Created: {fileInfo.CreationTime}\n" +
                      $"Modified: {fileInfo.LastWriteTime}\n" +
                      $"Extension: {fileInfo.Extension}";

        MessageBox.Show(info, "File Info");
    }
    else
    {
        MessageBox.Show("File not found.");
    }
}

πŸ“ Example: List All Files in a Folder

private void btnListFiles_Click(object sender, EventArgs e)
{
    string folderPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
    DirectoryInfo dir = new DirectoryInfo(folderPath);

    FileInfo[] files = dir.GetFiles();

    listBox1.Items.Clear();

    foreach (FileInfo file in files)
    {
        listBox1.Items.Add($"{file.Name} - {file.Length / 1024} KB");
    }
}

βœ… You get access to file size, type, and name in one place
βœ… Also supports filters: dir.GetFiles("*.txt")


πŸ“ Example: List Subfolders

private void btnListFolders_Click(object sender, EventArgs e)
{
    DirectoryInfo dir = new DirectoryInfo(@"C:\Users\Public");

    DirectoryInfo[] subDirs = dir.GetDirectories();

    listBox1.Items.Clear();

    foreach (DirectoryInfo sub in subDirs)
    {
        listBox1.Items.Add($"{sub.Name} - Created: {sub.CreationTime}");
    }
}

✨ Useful Properties and Methods

πŸ”Ή FileInfo

Property/MethodDescription
NameFile name only
FullNameFull path
LengthFile size in bytes
ExtensionFile type (e.g., .txt)
CreationTimeWhen the file was created
LastWriteTimeWhen it was last changed
Delete()Delete the file
CopyTo(dest)Copy the file

πŸ”Ή DirectoryInfo

Property/MethodDescription
NameFolder name
FullNameFull path
GetFiles()List of files in the folder
GetDirectories()List of subfolders
Create()Create the folder
Delete()Delete the folder

πŸ” Permissions Note

Attempting to access or delete system-protected files/folders may throw an error. Use try/catch to gracefully handle permission issues.

try
{
    fileInfo.Delete();
}
catch (Exception ex)
{
    MessageBox.Show("Error: " + ex.Message);
}

πŸ§ͺ Quick Challenge

🧩 Build a form with:

  • A TextBox for folder path
  • A Button to list .txt files
  • A ListBox to show file names and sizes

Bonus: Add a button to delete selected file using FileInfo.Delete().


πŸ“š Summary

ClassUse For
FileInfoGet file metadata, delete, copy files
DirectoryInfoList files/folders, create directories
GetFiles()Returns an array of FileInfo
GetDirectories()Returns array of DirectoryInfo

βœ… Best Practices

  • βœ… Use Path.Combine() when building paths
  • βœ… Always check Exists before working on a file/folder
  • βœ… Catch IO exceptions (permissions, locks, etc.)
  • βœ… Prefer relative or environment-based paths

πŸŽ“ Want to Go Further?

  • Combine with OpenFileDialog to inspect any file
  • Build a mini file explorer
  • Sort files by date or size using LINQ
  • Add support for renaming or moving files

πŸ’¬ Want to build a file manager or a diagnostics tool?
Tell us your idea β€” I’ll help you wire up FileInfo and DirectoryInfo for a professional experience.