![](/img/trans.png)
[英]Retrieve all .doc files exist in My Computer for a search term which user provides. Is it possible?
[英]Retrieve all pdf files that exist in My Computer
我有以下代碼從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);
您可以獲取所有驅動器,然后獲取所有文件。
編輯:您還可以使用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
}
}
您可以使用System.IO.DriveInfo類遍歷計算機上所有可用的驅動器(調用DriveInfo.GetDrives()以獲得所有驅動器的列表)。 您可能必須對每個驅動器都執行此操作,然后合並所有驅動器的結果。 我對當前代碼有什么問題的猜測是,給它MyComputer文件夾不足以告訴它遍歷所有驅動器。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.