Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/323.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用C#递归计算Windows中的文件和文件夹?_C#_Recursion_Filesystems_Directory - Fatal编程技术网

如何使用C#递归计算Windows中的文件和文件夹?

如何使用C#递归计算Windows中的文件和文件夹?,c#,recursion,filesystems,directory,C#,Recursion,Filesystems,Directory,编辑2012年8月8日:我对正在使用的代码做了一些重大更改,希望在最后一个问题上得到一些新的帮助。我将重写这个问题的大部分内容 我有一个小程序,它递归地遍历目标目录下的每个文件和文件夹,检查特定字符的名称。它工作得很好,但我正在寻求帮助,了解如何使特定方法更快地工作 这是我目前使用的代码。这只是启动一切的方法中的几行: if(getFullList(initialPathTB.Text)) SearchFolder(); 以下是您需要了解的两种方法: private

编辑2012年8月8日:我对正在使用的代码做了一些重大更改,希望在最后一个问题上得到一些新的帮助。我将重写这个问题的大部分内容

我有一个小程序,它递归地遍历目标目录下的每个文件和文件夹,检查特定字符的名称。它工作得很好,但我正在寻求帮助,了解如何使特定方法更快地工作

这是我目前使用的代码。这只是启动一切的方法中的几行:

if(getFullList(initialPathTB.Text))
            SearchFolder();  
以下是您需要了解的两种方法:

private void SearchFolder()
{
    int      newRow;
    int      numItems = 0;

    numItems = itemsMaster.Length;

    for (int x = 0; x < numItems; x++)
    {
        if (hasIllegalChars(itemsMaster[x]) == true)
        {
            newRow = dataGridView1.Rows.Add();
            dataGridView1.Rows[newRow].Cells[0].Value = itemsMaster[x];
            filesFound++;
        }
    }
}

private bool getFullList(string folderPath)
{
    try
    {
        if (checkBox17.Checked)
            itemsMaster = Directory.GetFileSystemEntries(folderPath, "*", SearchOption.AllDirectories);
        else
            itemsMaster = Directory.GetFileSystemEntries(folderPath, "*", SearchOption.TopDirectoryOnly);
        return true;
    }
    catch (UnauthorizedAccessException e)
    {
        if(folderPath[folderPath.Length - 1] != '\\')
            folderPath += @"\";
        if (e.Message == "Access to the path '" + folderPath + "' is denied.")
        {
            MessageBox.Show("You do not have read permission for the following directory:\n\n\t" + folderPath + "\n\nPlease select another folder or log in as a user with read access to this folder.", "Access Denied", MessageBoxButtons.OK, MessageBoxIcon.Error);
            folderPath = folderPath.Substring(0, folderPath.Length - 1);
        }
        else
        {
            if (accessDenied == null)
                accessDenied = new StringBuilder("");
            accessDenied.AppendLine(e.Message.Substring(20, e.Message.Length - 32));
        }
        return false;
    }
}
private void SearchFolder()
{
纽罗国际酒店;
int numItems=0;
numItems=itemsMaster.Length;
对于(int x=0;x
initialPathTB.Text
填充类似“F:\COMMON\Administration”的内容

这是我的问题。当传递给
folderPath
的顶层用户没有读取权限时,一切正常。当顶层目录和所有下级目录都是用户已读取访问权限的文件夹时,一切都会再次正常工作。问题在于用户对顶层有读取权限,但对深层子文件夹没有读取权限的目录。这就是为什么
getFullList()
是一个bool;如果存在任何未经授权的访问异常,则
itemsMaster
将保持为空,并且
SearchFolder()
numItems=itemsMaster.Length

我想用
folderPath
中的每个项目填充
itemsMaster
,只需跳过用户没有读取权限的项目,但我不知道如何在不递归爬网和检查每个目录的情况下完成

这段代码比我的旧方法快得多,所以我不想完全放弃它去做别的事情。有没有办法让
Directory.GetFileSystemEntries()
方法实现我想要的功能

Directory.GetFileSystemEntries(folderPath, "*", SearchOption.AllDirectories).Length
或者另一个选项(使用此选项时,请记住
fullstring
中的前3-5个元素将是输出中的垃圾文本,您应该删除它们):

您可以这样写:“我希望进度条实际指示程序在项目列表中的位置,因此我需要一些项目来设置ProgressBar.Maximum属性。”

这是一种特定的愿望,我不确定在给定的情况下它是否值得。如果你的ProgressBar是(比如)800像素宽,那么1个百分点就是0.125像素宽。对于一个“超过十万项”的列表——让我们将其设置为至少100000项——您必须处理8000项才能移动条以移动单个像素。您的程序处理8000个项目需要多少时间?这将有助于您了解您正在向用户提供什么样的实际反馈。如果时间太长,可能看起来事情已经悬而未决,即使它正在工作


如果您希望提供良好的用户反馈,我建议将ProgressBar的样式设置为Marquee,并提供“Now checking file#x”文本指示器

但这将大大落后于现代硬实力drive@ColeJohnson-这确实需要一段时间,但不像我的方法那样长。除非您想在非托管代码中执行此操作,否则我认为您执行此操作的速度不会比上述框架方法快得多。如果我使用
Directory.getfilesystemments(folderPath,“*”,SearchOption.AllDirectories)
填充数组,但在
文件夹路径下有一个或多个子目录,用户没有读取权限。catch子句如何处理
UnauthorizedAccessException
?它只是列出第一个文件并停止填充列表,还是继续填充下一个文件/目录?如果它继续运行,我是否有办法捕获引发异常的目录列表?@jonnyp如果您有后续问题,可以在评论中发布,我将尝试回答。与在Windows资源管理器中执行文件夹属性相比,您的程序计算需要多长时间?只是一个猜测,但我想你不会比Windows本身更快,因为Windows在这么大的东西上可能会非常慢。是否有必要使用
items[x]
上的
ToString()
?只是一个不必要的函数调用,它会导致延迟,尤其是在循环中。@JoeEnos-我的方法肯定比我通过Windows资源管理器检查文件夹属性花费的时间要长得多。只是出于兴趣,你的程序做什么,做什么
Process process = new Process();
List<string> fullstring = new List<string>();

process.StartInfo.FileName = "cmd.exe";
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardInput = true;
process.StartInfo.UseShellExecute = false;
process.OutputDataReceived += (sender, args2) => fullstring.Add(args2.Data);

process.Start();

process.StandardInput.WriteLine(@"dir /b /s c:\temp | find """" /v");
process.BeginOutputReadLine();

process.WaitForExit(10000); //or whatever is appropriate time

process.Close();
    process.OutputDataReceived += new DataReceivedEventHandler(process_OutputDataReceived);
}

static void process_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
    try
    {
        fullstring.Add(e.Data);
    }
    catch (Exception ex)
    {
        Debug.WriteLine(ex.ToString());
        //log exception
    }
}