【问题标题】:Get all files in a directory and all the files under all subdirectories获取一个目录下的所有文件以及所有子目录下的所有文件
【发布时间】:2013-12-31 13:22:42
【问题描述】:

我在获取所有文件夹和子目录下的所有文件时遇到了一点问题.. 并保留路径..

这是我此刻的代码..

这应该通过一切吧?所有子目录和一切?

private List<String> DirSearch(string sDir)
    {
        List<String> files = new List<String>();
        try
        {
            foreach (string f in Directory.GetFiles(sDir))
            {
                files.Add(f);
            }
            foreach (string d in Directory.GetDirectories(sDir))
            {
                files.AddRange(DirSearch(d));
            }
        }
        catch (System.Exception excpt)
        {
            MessageBox.Show(excpt.Message);
        }

        return files;
    }

但我得到的只是 1 个文件夹中的 1 个随机文件,许多子目录来自根文件夹。 这就是我所说的:

string folderName = folderBrowserDialog1.SelectedPath;
addFilesFromFolder(DirSearch(folderName));

这是将它们添加到 XML 文件的方法...

private void addFilesFromFolder(List<string> files)
    {
        String appDataFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData).ToString();
        String gpsPath = appDataFolder + "\\GameProfileSaver";

        XmlDocument doc = new XmlDocument();
        doc.Load(gpsPath + "\\games.xml");
        XmlNode fileToAdd = doc.CreateElement("file");
        String gName = comboBox1.SelectedItem.ToString();
        XmlNode gameName = doc.SelectSingleNode("//games/game[gameName='" + gName + "']/Files");

        foreach (string f in files)
        {
            fileToAdd.InnerText = f;
            gameName.AppendChild(fileToAdd);
        }

        doc.Save(gpsPath + "\\games.xml");
    }

【问题讨论】:

  • 你也可以看看this version of GetFiles。它通过 SearchOption 参数支持递归。
  • 你可以只做foreach (string f in Directory.GetFiles(sDir, "*", SearchOption.AllDirectories)) 而没有递归函数。

标签: c# file directory


【解决方案1】:

尝试将XmlNode fileToAdd = doc.CreateElement("file"); 移动到for 内:

XmlDocument doc = new XmlDocument();
doc.Load(gpsPath + "\\games.xml");
String gName = comboBox1.SelectedItem.ToString();
XmlNode gameName = doc.SelectSingleNode("//games/game[gameName='" + gName + "']/Files");

foreach (string f in files)
{
    XmlNode fileToAdd = doc.CreateElement("file");                
    fileToAdd.InnerText = f;
    gameName.AppendChild(fileToAdd);
}

我怀疑因为您正在重用XmlNode,所以您只能获取列表中的最后一个文件。

【讨论】:

  • 谢谢!这解决了我的问题……就这么简单……我没想过将它移到我的 foreach 中……
猜你喜欢
  • 2012-11-23
  • 1970-01-01
  • 1970-01-01
  • 2014-03-08
  • 1970-01-01
  • 2021-01-06
  • 2016-07-26
  • 1970-01-01
  • 2017-03-15
相关资源
最近更新 更多