I am currently developing a C# application to search a file in the computer. The GUI has two text fields: one for input(the name for the file to be searched) and one for displaying the path to the file (if it’s found).
Now, the problem is that my application is skipping my logical C: drive. Here is some piece of code:
foreach (string s in Directory.GetLogicalDrives() )
{
if (list.Count == 0)
{
foreach (string f in Directory.GetFiles(s, file))
{
textBox2.Text = f;
list.Add(f);
}
if (list.Count == 0)
{
search(s);
}
}
}
And the search method:
private void search(string sDir)
{
try
{
foreach (string d in Directory.GetDirectories(sDir))
{
if (list.Count == 0)
{
Console.WriteLine(d);
foreach (string f in Directory.GetFiles(d, file))
{
textBox2.Text = f;
list.Add(f);
}
if (list.Count == 0)
{
search(d);
}
}
}
}
catch (System.Exception excpt)
{
Console.WriteLine(excpt.Message);
}
}
Here is some output:
C:\$Recycle.Bin
C:\$Recycle.Bin\S-1-5-21-1794489696-3002174507-1726058468-1000
C:\Config.Msi
C:\de cautat
C:\de cautat\database
C:\de cautat\fut_bot
C:\de cautat\helper
C:\de cautat\images
C:\de cautat\itemiinfo
C:\de cautat\JSONs
C:\de cautat\JSONs\PLAYER
C:\de cautat\JSONs\USER
C:\de cautat\requests
C:\Documents and Settings
A first chance exception of type 'System.UnauthorizedAccessException' occurred in mscorlib.dll
Access to the path 'C:\Documents and Settings' is denied.
D:\$RECYCLE.BIN
D:\$RECYCLE.BIN\S-1-5-21-1794489696-3002174507-1726058468-1000
D:\$RECYCLE.BIN\S-1-5-21-2637989945-465084399-3498881169-1000
etc
Can anyone help me and tell what is the problem when accesing those folders? Thanks!
Note: I am using Microsoft Visual Studio 2010 on Windows 7 x64 (.NET Framework 2.0).
Move your try catch into the foreach (string d in Directory.GetDirectories(sDir)) loop so it continues to process on error.