Reputation: 23
I have below code to retrieve all pdf files from MyComputer. But i am getting error like below. Is it possible to retrive all pdf files from one computer using C# code.
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);
Upvotes: 0
Views: 3759
Reputation: 223187
You can get all drives and then get all files.
EDIT: You can also use Directory.EnumerateFiles
method which would let you get the file path and you can add that in your list. This would give you a List<string>
for all the file paths. Like:
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
}
}
Old Answer.
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
}
}
Upvotes: 9
Reputation: 167
You can use the System.IO.DriveInfo class to loop through all drives available on the machine (call DriveInfo.GetDrives() to get a list of all drives). You will probably have to do this for each drive and combine the results from all of them. My guess with what is wrong with your current code is that giving it the MyComputer folder isn't enough to tell it to loop through all drives.
Upvotes: 0