[英]Get all files in a directory and all the files under all subdirectories
我在獲取所有文件夾和子目錄下的所有文件時遇到了一個小問題。並保留路徑。
此刻是我的代碼。
這應該經歷所有正確的事情嗎? 所有子目錄以及所有內容?
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");
}
嘗試移動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
,所以您只會得到列表中的最后一個文件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.