DriveStatisticsRepository
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace Relativity.Transfer
{
internal class DriveStatisticsRepository
{
private const string LongPathPrefix = "\\\\?\\";
public static IEnumerable<DriveStatistics> GetAllDrives()
{
List<DriveStatistics> list = new List<DriveStatistics>();
DriveInfo[] drives = DriveInfo.GetDrives();
foreach (DriveInfo driveInfo in drives) {
long totalSpace = 0;
long totalFreeSpace = 0;
string errorMessage = "N/A";
try {
totalSpace = driveInfo.TotalSize;
totalFreeSpace = driveInfo.TotalFreeSpace;
} catch (UnauthorizedAccessException) {
errorMessage = "Access to the drive information is denied";
} catch (DriveNotFoundException) {
errorMessage = "The drive is not mapped or does not exist.";
} catch (IOException) {
errorMessage = "An I/O error occurred (for example, a disk error or a drive was not ready)";
} finally {
list.Add(new DriveStatistics(driveInfo.DriveType, driveInfo.Name, totalSpace, totalFreeSpace, errorMessage));
}
}
return list;
}
public static long GetAvailableFreeSpace(string path, out float freeFraction)
{
freeFraction = 1;
if (string.IsNullOrEmpty(path))
return 9223372036854775807;
string text = IsLongPath(path) ? path.Substring("\\\\?\\".Length) : path;
if (string.IsNullOrEmpty(text))
return 9223372036854775807;
string pathRoot = Path.GetPathRoot(text);
if (string.IsNullOrEmpty(pathRoot))
return 9223372036854775807;
DriveInfo driveInfo = DriveInfo.GetDrives().FirstOrDefault((DriveInfo x) => x.Name.Equals(pathRoot, StringComparison.OrdinalIgnoreCase));
if (driveInfo == null)
return 9223372036854775807;
freeFraction = (float)driveInfo.AvailableFreeSpace / (float)driveInfo.TotalSize;
return driveInfo.AvailableFreeSpace;
}
private static bool IsLongPath(string path)
{
return path.StartsWith("\\\\?\\");
}
}
}