[试图获取文件名时抛出System.IO.IOException

问题描述 投票:0回答:1

我正在计算指定目录其中包含大量数据中最近一次写入时间早于10分钟的所有文件的总大小。这是我在下面尝试过的代码:

DateTime from_date = DateTime.Now.AddMinutes(-10);
List<string> list = Directory.GetFiles(@[PATH], "*", SearchOption.AllDirectories)               
            .Where(x => File.GetLastWriteTime(x).Date > from_date)
            .Select(x => new FileInfo(x).FullName)
            .ToList();            

foreach (String s in list)
{
    FileInfo file = new FileInfo(s);
    size += file.Length;
}

button6.Text = ((size / 1024f) / 1024f) + "MB";

这在我指定local路径时有效,但是在指定网络路径时会抛出< IOException。为什么会发生?有没有一种方法可以让我“持有”网络路径或确保与该路径的连接不会失败?

c#-4.0 networking ioexception
1个回答
0
投票
DirectoryInfo.EnumerateFiles()DirectoryInfo.EnumerateDirectories是最佳选择。

var directories = new DirectoryInfo(root).EnumerateDirectories().OrderByDescending(d => d.Name); IEnumerable<FileInfo> files; foreach (DirectoryInfo directoryInfo in directories) { files = directoryInfo .EnumerateFiles("*" + extension, SearchOption.AllDirectories) .OrderByDescending(f => f.LastWriteTime); foreach (FileInfo f in files) { if ((f.LastWriteTime.CompareTo(DateTime.Now.AddMinutes(-10)) == 1) { // Do whatever you want with the files } } }

© www.soinside.com 2019 - 2024. All rights reserved.