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

时间:2013-10-25 12:31:20

标签: c#-4.0 networking ioexception

我正在尝试计算所有文件的总大小,其中上次写入时间早于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";

当我指定本地路径时,这会有效,但在指定网络路径时会抛出网络名称不再可用 IOException。为什么会这样?有没有办法可以“保持”网络路径或确保与此路径的连接不会失败?

1 个答案:

答案 0 :(得分:0)

DirectoryInfo.EnumerateFiles()和DirectoryInfo.EnumerateDirectories是最佳选择。

IEnumerable<DirectoryInfo> 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
                }
            }