我每次运行应用程序时都需要一些视频文件。它检查HD
可用空间是否小于1千兆字节,如果为真则继续删除最旧的日期文件,依此类推,直到有足够的可用空间为止。
foreach (DriveInfo drive in DriveInfo.GetDrives())
{
if (drive.IsReady && drive.Name == "E:\\")
{
if (drive.TotalFreeSpace < 10000000)
{
do
{
DirectoryInfo info = new DirectoryInfo(@"E:\REC\Video\");
FileInfo[] files = info.GetFiles().OrderBy(p => p.LastWriteTime).ToArray();
System.IO.File.Delete(@"E:\REC\Video\" + files[0].Name);
}
while (drive.TotalFreeSpace < 10000000);
}
}
}
vidofiles会在几个月内自动生成(录音)。
那么:如何测试此代码而不必等到我的磁盘空间已满?
答案 0 :(得分:0)
我测试了它,我更换10000000,所以我右键单击驱动器并复制当前的空闲空间添加一些字节,它工作,我不得不改变它,就像这样:
foreach (DriveInfo drive in DriveInfo.GetDrives())
{
if (drive.IsReady && drive.Name == "E:\\")
{
if (drive.TotalFreeSpace <= 245000000000000)
{
try
{
while (drive.TotalFreeSpace <= 245000000000000)
{
DirectoryInfo info = new DirectoryInfo(@"E:\REC\Video\");
FileInfo[] files = info.GetFiles().OrderBy(p => p.LastWriteTime).ToArray();
System.IO.File.Delete(@"E:\REC\Video\" + files[0].Name);
}
}
catch
{
}
}
}
}
答案 1 :(得分:0)
我会将代码放在自己的方法中。将所需的磁盘空间放在参数中:
public class HdCleaner
{
public static void DeleteOldestFiles(long minimumAvailableSpace, string path)
{
var driveLetter = Path.GetPathRoot(path);
var drive1 = DriveInfo.GetDrives().Where(d => d.IsReady).Single(d => d.Name == driveLetter);
while (drive1.TotalFreeSpace <= minimumAvailableSpace)
{
var info = new DirectoryInfo(path);
var file = info.GetFiles().OrderBy(p => p.LastWriteTime).First();
file.Delete();
}
}
}
进行测试进行单元测试: 确保路径中有一些文件可以删除。
[TestMethod]
public void DeleteOldestFilesTest()
{
const string driveLetter = "C:\\";
const string path = "C:\\Users\\user\\FileCleanerTest";
var drive = DriveInfo.GetDrives().Where(d => d.IsReady).Single(d => d.Name == driveLetter);
var availableSpace = drive.TotalFreeSpace;
var neededSpace = availableSpace + 10000;
HdCleaner.DeleteOldestFiles(neededSpace, path);
var newAvailableSpace = drive.TotalFreeSpace;
Assert.IsTrue(newAvailableSpace >= neededSpace);
}
P.S。:我做了一些重构;)