问题
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