您可以獲取所有驅動器,然後獲取所有文件。
編輯:你也可以使用Directory.EnumerateFiles
方法,它可以讓你獲得文件路徑,你可以將它添加到你的列表中。這將爲您提供所有文件路徑的List<string>
。像:
List<string> filePathList = new List<string>();
foreach (DriveInfo drive in DriveInfo.GetDrives())
{
try
{
var filenames = Directory.EnumerateFiles(drive.Name, "*.pdf", SearchOption.AllDirectories);
foreach (string fileName in filenames)
{
filePathList.Add(fileName);
}
}
catch (FieldAccessException ex)
{
//Log, handle Exception
}
catch (UnauthorizedAccessException ex)
{
//Log, handle Exception
}
catch (Exception ex)
{
//log , handle all other exceptions
}
}
舊的答案。
List<FileInfo> fileList = new List<FileInfo>();
foreach (var drive in System.IO.DriveInfo.GetDrives())
{
try
{
DirectoryInfo dirInfo = new DirectoryInfo(drive.Name);
foreach (var file in dirInfo.GetFiles("*.pdf", SearchOption.AllDirectories))
fileList.Add(file);
}
catch (FieldAccessException ex)
{
//Log, handle Exception
}
catch (UnauthorizedAccessException ex)
{
//Log, handle Exception
}
catch (Exception ex)
{
//log , handle all other exceptions
}
}
傳遞給'DirectoryInfo'構造函數的路徑的值是什麼? – evanmcdonnal
錯誤只是說,你指定一個非法的路徑。 – user959631
您需要查看所有驅動器(請參閱http://stackoverflow.com/questions/781905/getting-a-list-of-logical-drives),並在子文件夾內遞歸地運行 –