我有一些视频文件,我需要每次我运行我的应用程序。它检查HD
的可用空间是否小于1千兆字节,如果是真的,继续删除最旧的日期文件等,直到有足够的可用空间。
foreach (DriveInfo drive in DriveInfo.GetDrives())
{
if (drive.IsReady && drive.Name == "E:\")
{
if (drive.TotalFreeSpace < 10000000)
{
do
{
DirectoryInfo info = new DirectoryInfo(@"E:RECVideo");
FileInfo[] files = info.GetFiles().OrderBy(p => p.LastWriteTime).ToArray();
System.IO.File.Delete(@"E:RECVideo" + files[0].Name);
}
while (drive.TotalFreeSpace < 10000000);
}
}
}
视频文件是在几个月的时间里自动生成(录制)的。
所以:我如何测试这段代码,而不必等到我的磁盘空间满了?
我会把代码放在它自己的方法中。将所需的磁盘空间放入参数中:
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);
}
注::我做了一些重构;)
我测试了它,我替换了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:RECVideo");
FileInfo[] files = info.GetFiles().OrderBy(p => p.LastWriteTime).ToArray();
System.IO.File.Delete(@"E:RECVideo" + files[0].Name);
}
}
catch
{
}
}
}
}