Get all files in a directory and all the files under all subdirectories

邮差的信 提交于 2019-12-25 06:44:22

问题


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

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

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

回答1:


Try moving XmlNode fileToAdd = doc.CreateElement("file"); inside the 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);
}

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



来源:https://stackoverflow.com/questions/20555246/get-all-files-in-a-directory-and-all-the-files-under-all-subdirectories

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!