我正在尝试读取XML文档的目录列表,并将其存储到列表中,然后我将获得子目录。我正在测试此内容,并且可以从XML文档中获取目录,但是当我尝试获取子目录时,我会收到以下错误:找不到路径" C: test1"的一部分。我已经查看了其他类似的答案,但无法找到解决我的问题的方法。我尝试使用前进和没有结肠的前向斜线和后斜线,但仍然没有运气。
这是xml
<Options>
<Directories>
<Directory>C:/Test1/</Directory>
<Directory>C:/Test2/</Directory>
<Directory>C:/Test3/</Directory>
</Directories>
<DeleteTime>30</DeleteTime>
</Options>
这是我的C#代码:
static void Main(string[] args)
{
//Declaring variables for use later
List<string> directories = new List<string>();
List<FileInfo> fileList = new List<FileInfo>();
//Load Directories from XML
XElement Options = XElement.Load("C:/Directories.xml");
IEnumerable<XElement> DirList =
from dir in Options.Descendants("Directory")
select dir;
foreach (XElement dirName in DirList)
{
directories.Add((string)dirName);
}
//Converting XML strings to Directories and adding all subfolders over 30 seconds old to a delete list
foreach (var directory in directories)
{
DirectoryInfo dirItem = new DirectoryInfo(directory);
var folderList = dirItem.GetDirectories();
Console.WriteLine(folderList);
}
}
我复制了您的代码并设置了它所描述的目录结构,所有这些都对我有用。
我唯一要做的就是将所有前进斜线更改为后斜线。
<Options>
<Directories>
<Directory>C:Test1</Directory>
<Directory>C:Test2</Directory>
<Directory>C:Test3</Directory>
</Directories>
<DeleteTime>30</DeleteTime>
</Options>
和c#:
class Program
{
static void Main(string[] args)
{
//Declaring variables for use later
List<string> directories = new List<string>();
List<FileInfo> fileList = new List<FileInfo>();
//Load Directories from XML
XElement Options = XElement.Load(@"C:Directories.xml");
IEnumerable<XElement> DirList =
from dir in Options.Descendants("Directory")
select dir;
foreach (XElement dirName in DirList)
{
directories.Add((string)dirName);
}
//Converting XML strings to Directories and adding all subfolders over 30 seconds old to a delete list
foreach (var directory in directories)
{
DirectoryInfo dirItem = new DirectoryInfo(directory);
var folderList = dirItem.GetDirectories();
Console.WriteLine(folderList);
}
}
}
我建议您检查并确保该过程有权查看目录,并且您不会意外地将后斜线视为逃生字符而不是文件路径。在我的示例中,我用 @来避免这种情况。