程序浏览目录并将Avi文件打印到文本框
public FileList()
{
InitializeComponent();
//Sets Drive Choices
DriveInfo[] drives = DriveInfo.GetDrives();
foreach (DriveInfo d in drives)
{
driveChoice.Items.Add(d);
}
}
//Find Video Files
private void btnStart_Click(object sender, EventArgs e)
{
String path = driveChoice.Text;
if (path != "C:\\")
{
String[] allfiles = Directory.GetFiles(path, "*.avi*", System.IO.SearchOption.AllDirectories);
foreach (String file in allfiles)
{
tbFileList.Text = tbFileList.Text + file + "\r\n";
}
}
else
{
Application.Exit();
}
}
}
public FileList()
{
InitializeComponent();
//Sets Drive Choices
DriveInfo[] drives = DriveInfo.GetDrives();
foreach (DriveInfo d in drives)
{
driveChoice.Items.Add(d);
}
}
//Find Video Files
private void btnStart_Click(object sender, EventArgs e)
{
String path = driveChoice.Text;
if (path != "C:\\")
{
String[] allfiles = Directory.GetFiles(path, "*.avi*", System.IO.SearchOption.AllDirectories);
foreach (String file in allfiles)
{
tbFileList.Text = tbFileList.Text + file + "\r\n";
}
}
else
{
Application.Exit();
}
}
}
跑步时我收到错误。
未经授权访问'I:\ $ RECYCLE.BIN \ S-1-5-21-1332477098-3306142970-3529014387-1000 \'
我可以将程序设置为跳过'I:\ $ RECYCLE.BIN'
答案 0 :(得分:2)
现在没有办法让AllDirectories
选项跳过特定目录或忽略遍历时发生的异常。您需要手动搜索目录结构并处理发生的错误
答案 1 :(得分:2)
看起来你需要切换到递归解决方案或其他循环,而不是使用'AllDirectories'。这样你就可以提供一些跳过逻辑。
请参阅此链接http://support.microsoft.com/kb/303974
以及该页面中的以下代码段:
void DirSearch(string sDir)
{
try
{
foreach (string d in Directory.GetDirectories(sDir))
{
foreach (string f in Directory.GetFiles(d, txtFile.Text))
{
lstFilesFound.Items.Add(f);
}
DirSearch(d);
}
}
catch (System.Exception excpt)
{
Console.WriteLine(excpt.Message);
}
}
在该代码中,您只需检查您的sDir以查找要跳过的值。
答案 2 :(得分:0)
if !filePath.Contains("I:\$RECYCLE.BIN")
答案 3 :(得分:0)
使用lambda语句排除系统目录:
public FileList()
{
InitializeComponent();
//Sets Drive Choices
DriveInfo[] drives = DriveInfo.GetDrives();
foreach (DriveInfo d in drives)
{
driveChoice.Items.Add(d);
}
}
//Find Video Files
private void btnStart_Click(object sender, EventArgs e)
{
String path = driveChoice.Text;
if (path != "C:\\")
{
DirectoryInfo root = new DirectoryInfo(path);
var rootFiles = root.GetFiles("*.avi");
var rootDirs = root.GetDirectories("*", SearchOption.TopDirectoryOnly).Where(d => !d.Name.Equals("System Volume Information") && !d.Name.Equals("$RECYCLE.BIN"));
foreach (var file in rootFiles)
{
tbFileList.Text = tbFileList.Text + file.FullName + "\r\n";
}
foreach (var dir in rootDirs)
{
foreach (var dirFile in dir.GetFiles("*.avi", SearchOption.AllDirectories))
{
tbFileList.Text = tbFileList.Text + dirFile.FullName + "\r\n";
}
}
}
else
{
Application.Exit();
}
}
答案 4 :(得分:0)
我刚尝试使用Lambda表达式,将VS 2017中返回的字符串列表中的两个文件夹都排除在外。如果将lambda表达式直接添加到目录的检索中,如列表中上方的字符串所示,列表仍将返回$ RECYCLEBIN,但是不会返回SVI文件夹。为了使lambda正常工作,我需要将2个操作分开,即:
var allDirs = rootDir.GetDirectories("*",SearchOption.TopDirectoryOnly);
var filteredDirs = allDirs.Where(d=> !d.Name.Equals("System Volume Information") && !d.Name.Equals("$RECYCLE.BIN"));