use*_*358 0 .net c# filesystems c#-4.0
我有以下代码从MyComputer检索所有pdf文件.但我得到的错误如下.是否可以使用C#代码从一台计算机中检索所有pdf文件.
string path = Environment.GetFolderPath(Environment.SpecialFolder.MyComputer);
System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(path); // Error : The path is not of a legal form.
IEnumerable<System.IO.FileInfo> fileList = dir.GetFiles("*.pdf", System.IO.SearchOption.AllDirectories);
Run Code Online (Sandbox Code Playgroud)
您可以获取所有驱动器,然后获取所有文件.
编辑:你也可以使用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
}
}
Run Code Online (Sandbox Code Playgroud)
老答案.
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
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2306 次 |
| 最近记录: |