【问题标题】:C# - Search for Matching FileNames in a Directory using SearchOptionC# - 使用 SearchOption 在目录中搜索匹配的文件名
【发布时间】:2011-03-23 19:32:27
【问题描述】:

背景:我正在使用带有 OpenFileDialog 和 FileBrowserDialog 的 C# 开发 WinForms 应用程序,它将 1)在指定源目录的文件名中搜索特定字符串 2)将文件复制到合并目录 3)从 excel 转换多个文件到 csv 文件,然后 3) 使用命令行可执行文件将所有生成的 csv 文件转换为 1 个大 csv 文件

示例:MSDN 提供了一个代码示例,列出了“c:\”中所有以字母“c”开头的目录和文件。在http://msdn.microsoft.com/en-us/library/ms143448.aspx,所以我的代码基于此...

问题:代码不会将任何文件复制到合并文件夹中,因此我很确定搜索不起作用。

我应该在这里改变什么?它不起作用:

    string files = "*.xlsx";
    void DirSearch(string sDir)
    {
        try
        {
            foreach (string d in Directory.GetDirectories(sDir))
            {
                foreach (string f in Directory.GetFiles(d, files))
                {
                    // Is this the file we are looking for?
                    // check excel files for corp name in the filename.
                    if (f.Contains(m_sc.get_Corp()))
                    {
                        // check if thread is cancelled
                        if (m_EventStop.WaitOne(0, true))
                        {
                            // clean-up operations may be placed here
                            // ...

                            // inform main thread that this thread stopped
                            m_EventStopped.Set();

                            return;
                        }
                        else
                        {
                            string path = sDir;
                            string searchPattern = m_sc.get_Corp();

                            // A file has been found in this directory
                            DirectoryInfo di = new DirectoryInfo(path);
                            DirectoryInfo[] directories = di.GetDirectories(searchPattern, SearchOption.TopDirectoryOnly);

                            foreach (FileInfo file in files)
                            {

                              try
                              {
                              // Copy each selected xlsx files into the specified TargetFolder 

                              System.IO.File.Copy(FileName, consolidatedFolder + @"\" + System.IO.Path.GetFileName(FileName));
                              Log("File" + FileName + " has been copied to " + consolidatedFolder + @"\" + System.IO.Path.GetFileName(sourceFileOpenFileDialog.FileName));

                             // Convert each selected XLSX File to CSV Using the command prompt code... 
                              }
                            }
                       }
                  }

【问题讨论】:

  • @JoshM,我删除了一半的其他代码,这样代码更容易分析。该代码不会将任何文件复制到合并文件夹中,因此我很确定搜索不起作用。
  • 你调试了吗?这将是查看搜索是否返回任何内容的第一步......
  • 你有 foreach (FileInfo file in files) 这意味着 files 是 FileInfo 类型,但是你有 string files = ".xlsx" 或者是一个错字
  • 需要更多信息。如果完全出错,你会得到什么错误。什么是行不通的,代码在哪里?此外,您不需要两个循环并递归调用 DirSearch 方法。而是使用: string[] filesNames = Directory.GetFiles(sDir, files, SearchOption.AllDirectories); foreach(文件名中的字符串 d){

标签: c# winforms search process


【解决方案1】:

您发布的代码执行两个独立的搜索循环:

第一:

    foreach (string d in Directory.GetDirectories(sDir))
    {
        foreach (string f in Directory.GetFiles(d, files))
        {
            // Is this the file we are looking for?
            // check excel files for corp name in the filename.
            if (f.Contains(m_sc.get_Corp()))
            {

然后在其中它也这样做: 字符串路径 = sDir; 字符串搜索模式 = m_sc.get_Corp();

                        // A file has been found in this directory
                        DirectoryInfo di = new DirectoryInfo(path);
                        DirectoryInfo[] directories = di.GetDirectories(searchPattern, SearchOption.TopDirectoryOnly);

                        foreach (FileInfo file in files)
                        {

在第一个中您正在寻找与m_sc.get_Corp(); 匹配的文件,在第二个中您正在寻找目录...

事实上……你的代码(伪代码?)毫无意义……

试试:

  • 慢慢来
  • 自己整理代码
  • 如果你慢慢地重写它并将它分成更小的块,你可能会发现你做错了什么。

【讨论】:

  • +1 用于清理乱七八糟的东西...最近这里有很多废话(废话 = 不是很干净,重复的代码块,方法做 20 件事等)
  • @Stuart,+1 感谢您的回复。开始筛选的代码有点多,所以我一直马虎并犯错误。好决定。我想我会删除那里的一些 cmets。您如何建议我缩短了 csv 转换和合并的代码行数?
  • 我实际上只是调试它来查看问题。如果我正在调试这段代码,我只需在第一行放置一个断点,然后在每个内部循环的第一行放置一个断点......您很快就会发现正在调用哪些代码行并且监视窗口将告诉你每一行发生了什么。一旦你发现一行代码不符合你的预期,那么你可以创建一个新的更小的函数来运行那一小段代码——要么自己解决那个小函数的问题——要么回到这里提出一个特定的问题。希望对您有所帮助:) Stuart(一个气囊!)
  • @Stuart,即使我将它设置为 true,多选也不起作用。你知道为什么会这样吗?
  • “多选不起作用”对我来说毫无意义。你的代码的哪一点是多选的? “不起作用”是什么意思 - 它会引发异常吗?它返回null吗?请给我们一些工作!
【解决方案2】:

试着清理一下,下面是一些可以让你走上正轨的代码,我已经排除了 CSV 转换和合并,希望你能明白。

  private void YourFileRoutine(string sourceDirectoryPath, string consolidatedDirectoryPath)
    {
        var excelFiles = new DirectoryInfo(sourceDirectoryPath).GetFiles().Where(x => x.Extension == ".xlsx");

        //Copy all Excel Files to consolidated Directory
        foreach (var excelFile in excelFiles)
        {
            FileInfo copiedFile = excelFile.CopyTo(String.Concat(consolidatedDirectoryPath, excelFile.Name)); // Make sure consolidatedDirectoryPath as a "\" maybe use Path.Combine()?

            // ConvertToCSV( Do your CSV conversion here, the Path will be = Path.GetFullPath(copiedFile);
        }

        // Merge CSV's
        var csvFiles = new DirectoryInfo(consolidatedDirectoryPath).GetFiles().Where(x => x.Extension == ".csv");
        // SomeMergeMethod that iterates through this FileInfo collection?

    }

【讨论】:

  • +1 感谢您的回复。不过,我该如何适应我的代码呢?
  • 分步执行,看看能否将excel文件复制到新位置,完成后进行csv转换合并。所以只要看看你是否可以让第一个 foreach 工作并删除 csv 部分以首先确保文件副本正常工作。
猜你喜欢
  • 2013-10-21
  • 1970-01-01
  • 2021-12-10
  • 1970-01-01
  • 1970-01-01
  • 2018-12-27
  • 1970-01-01
  • 2018-12-24
  • 2012-04-28
相关资源
最近更新 更多