【发布时间】:2016-02-19 11:54:02
【问题描述】:
我正在创建一个 c# 扫描目录的备份应用程序。在我使用这样的东西来获取目录中的所有文件和子文件之前:
DirectoryInfo di = new DirectoryInfo("A:\\");
var directories= di.GetFiles("*", SearchOption.AllDirectories);
foreach (FileInfo d in directories)
{
//Add files to a list so that later they can be compared to see if each file
// needs to be copid or not
}
唯一的问题是有时无法访问文件并且我遇到了几个错误。我得到的错误示例是:
因此,我创建了一个递归方法,它将扫描当前目录中的所有文件。如果该目录中有目录,则将再次调用该方法并传递该目录。这种方法的好处是我可以将文件放在 try catch 块中,如果没有错误,我可以选择将这些文件添加到列表中,如果有错误,我可以将目录添加到另一个列表中。
try
{
files = di.GetFiles(searchPattern, SearchOption.TopDirectoryOnly);
}
catch
{
//info of this folder was not able to get
lstFilesErrors.Add(sDir(di));
return;
}
所以这个方法很好用,唯一的问题是当我扫描一个大目录时需要很多次。我怎样才能加快这个过程?我的实际方法是这样,以备不时之需。
private void startScan(DirectoryInfo di)
{
//lstFilesErrors is a list of MyFile objects
// I created that class because I wanted to store more specific information
// about a file such as its comparePath name and other properties that I need
// in order to compare it with another list
// lstFiles is a list of MyFile objects that store all the files
// that are contained in path that I want to scan
FileInfo[] files = null;
DirectoryInfo[] directories = null;
string searchPattern = "*.*";
try
{
files = di.GetFiles(searchPattern, SearchOption.TopDirectoryOnly);
}
catch
{
//info of this folder was not able to get
lstFilesErrors.Add(sDir(di));
return;
}
// if there are files in the directory then add those files to the list
if (files != null)
{
foreach (FileInfo f in files)
{
lstFiles.Add(sFile(f));
}
}
try
{
directories = di.GetDirectories(searchPattern, SearchOption.TopDirectoryOnly);
}
catch
{
lstFilesErrors.Add(sDir(di));
return;
}
// if that directory has more directories then add them to the list then
// execute this function
if (directories != null)
foreach (DirectoryInfo d in directories)
{
FileInfo[] subFiles = null;
DirectoryInfo[] subDir = null;
bool isThereAnError = false;
try
{
subFiles = d.GetFiles();
subDir = d.GetDirectories();
}
catch
{
isThereAnError = true;
}
if (isThereAnError)
lstFilesErrors.Add(sDir(d));
else
{
lstFiles.Add(sDir(d));
startScan(d);
}
}
}
如果我尝试使用以下方式处理异常,则会出现问题:
DirectoryInfo di = new DirectoryInfo("A:\\");
FileInfo[] directories = null;
try
{
directories = di.GetFiles("*", SearchOption.AllDirectories);
}
catch (UnauthorizedAccessException e)
{
Console.WriteLine("There was an error with UnauthorizedAccessException");
}
catch
{
Console.WriteLine("There was antother error");
}
如果发生异常,我就没有文件了。
【问题讨论】:
-
您应该只捕获特定的异常(例如
UnauthorisedAccessException),而不是捕获所有内容,否则编程(例如NullReferenceException)和系统错误(例如OutOfMemoryException)将被屏蔽为应用程序错误. -
所需时间取决于层次结构中的文件数量。如果有很多文件,这将需要很长时间。就是这样。
-
顺便说一下,我在这里展示了一个更简单的递归目录列表方法:informit.com/guides/content.aspx?g=dotnet&seqNum=159。您可以修改该代码以处理异常并将内容存储在您的列表中。
标签: c# performance fileinfo