获取目录中的所有文件以及所有子目录下的所有文件 [英] Get all files in a directory and all the files under all subdirectories

查看:325
本文介绍了获取目录中的所有文件以及所有子目录下的所有文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到所有文件夹和子目录下的所有文件有一个小问题..并保持路径。

I'm having a little problem getting all the files under all folders and sub directories.. And keep the path..

这是我的代码在这一刻..

Here is my code at this moment..

这应该是正确的吗?所有子目录和所有内容?

This should go through everything right? All sub directories and everything?

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个随机文件许多子目录从根文件夹。
这就是我称之为:

But all I'm getting is 1 random file in 1 folder many sub directories from the root folder. And this is how i call it:

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

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

And this is the method that's adding them to an XML file...

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");
    }


推荐答案

尝试移动 XmlNode fileToAdd = doc.CreateElement(file);

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 ,您只能收到列表中的最后一个文件。

I suspect because you are reusing the XmlNode, you are only getting the last file in the list.

这篇关于获取目录中的所有文件以及所有子目录下的所有文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆