Directories and Files
Working with directories and files in desktop WinUI apps often requires translating raw metadata into something meaningful for users. The snippets below show how to gather storage information safely, even when paths are missing or access is restricted.
Read folder size
Reads the folder size and returns a string with a readable size (e.g. 5 KB, 10 MB):
/// <summary>/// Returns the size of a folder in human-readable format/// </summary>/// <param name="folderPath"></param>/// <returns></returns>private static string GetReadableFolderSize(string folderPath){ if (!Directory.Exists(folderPath)) { return string.Empty; }
// Sum up the size of all files in the folder var sizeInBytes = Directory.GetFiles(folderPath, "*.*", SearchOption.AllDirectories).Sum(filePath => new FileInfo(filePath).Length);
// Convert size to readable form return ConvertBytesToReadableSize(sizeInBytes);}
/// <summary>/// Converts bytes into readable sizes/// </summary>/// <param name="bytes"></param>/// <returns></returns>private static string ConvertBytesToReadableSize(long bytes){ string[] sizes = { "B", "KB", "MB", "GB", "TB" }; double formattedSize = bytes; var sizeIndex = 0;
while (formattedSize >= 1024 && sizeIndex < sizes.Length - 1) { formattedSize /= 1024; sizeIndex++; }
return $"{formattedSize:n2} {sizes[sizeIndex]}";}Read last modified
Returns the date and time the folder or file was last modified:
/// <summary>/// Returns the last modified date of a file or folder/// </summary>/// <param name="path"></param>/// <returns></returns>public static DateTime GetLastModifiedDate(string path){ if (File.Exists(path)) { // This is a file return new FileInfo(path).LastWriteTime; }
return Directory.Exists(path) // It is a folder ? new DirectoryInfo(path).LastWriteTime : DateTime.MinValue;}Usage tips
- Normalize user-supplied paths with
Path.GetFullPathto prevent directory traversal issues when you accept input. - Cache repeated directory scans when presenting results in the UI—scanning large trees can be expensive.
- Combine the helper with
ObservableCollectionorINotifyPropertyChangedso size and date updates propagate to your view models.
Handling exceptions
Wrap file system access in try/catch blocks to provide friendly error messages when access is denied:
public static DateTime? TryGetLastModifiedDate(string path, out string error){ error = string.Empty;
try { return GetLastModifiedDate(path); } catch (UnauthorizedAccessException ex) { error = $"Access to {path} is not permitted: {ex.Message}"; } catch (IOException ex) { error = $"Unable to read {path}: {ex.Message}"; }
return null;}