我目前正在开发一个 C# 应用程序来搜索计算机中的文件。 GUI 有两个文本字段:一个用于输入(要搜索的文件的名称),一个用于显示文件的路径(如果找到)。
现在,问题是我的应用程序正在跳过我的逻辑 C: 驱动器。这是一些代码:
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);
}
}
}
和搜索方法:
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);
}
}
这是一些输出:
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
任何人都可以帮助我并告诉我访问这些文件夹时出现了什么问题吗?谢谢!
注意:我在 Windows 7 x64 (.NET Framework 2.0) 上使用 Microsoft Visual Studio 2010。
最佳答案
问题是您正在访问您没有读取权限的文件夹。您将需要以管理员身份运行您的程序,或者需要让它跳过您没有读取权限的文件和文件夹。使用 Directory.EnumerateFiles
将使您简化代码,并且它不应尝试打开它没有读取权限的文件夹。
foreach (string s in Directory.GetLogicalDrives())
{
if (list.Count == 0)
{
foreach (string f in Directory.EnumerateFiles(s, file, SerchOption.AllDirectories))
{
try
{
textBox2.Text = f;
list.Add(f);
}
catch (System.Exception excpt)
{
Console.WriteLine(excpt.Message);
}
}
}
}
关于C# 在计算机中搜索文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8511892/