Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#Linq到XML检查目录是否存在_C#_Xml_Linq - Fatal编程技术网

C#Linq到XML检查目录是否存在

C#Linq到XML检查目录是否存在,c#,xml,linq,C#,Xml,Linq,我有以下XML文件布局: 下面是我混合在一起的frankencode: TopNode.Add(new XElement("AppRun", new XAttribute("Date", DateTime.Now.ToString("dd-MMM-yy hh:mm")), _folderNameArray.Select(x => new XElement("Folder", new XAttribute("Name", x

我有以下XML文件布局:


下面是我混合在一起的frankencode:

        TopNode.Add(new XElement("AppRun",
            new XAttribute("Date", DateTime.Now.ToString("dd-MMM-yy hh:mm")),
            _folderNameArray.Select(x => new XElement("Folder", new XAttribute("Name", x),
                Directory.GetDirectories(Path.Combine(_sourceDirectory, x), "*", SearchOption.TopDirectoryOnly).
                                             Select(y => new XElement("SubFolder", new XAttribute("Name", Path.GetFileNameWithoutExtension(y))))))));
所以我在数组中有文件夹元素名,因为它们保持不变;但是,文件夹可能并不总是存在。因此,当应用程序尝试创建目录时,它将抛出DirectoryNotFound异常。我希望在xml中保留一个空文件夹元素,即使该目录不存在


有人能告诉我正确的方向来编辑这段代码以检查目录是否存在,然后再尝试探测它。

这将获得文件夹列表中的所有子文件夹

var mainFolder = "C:\\";
            var folders = new []{ "Test" , "ABCFG" };

            var data = new XElement("AppRun", 
                       from folderName in folders
                       let path = Path.Combine(mainFolder,folderName)
                       select new XElement("Folder", 
                           new XAttribute("Name",folderName), 
                           Directory.Exists(path) ? from subDir in  Directory.GetDirectories(path, "*", SearchOption.TopDirectoryOnly)
                                                    select new XElement("SubFolder",new XAttribute("Name", Path.GetFileNameWithoutExtension(subDir))): null));

            Console.WriteLine(data.ToString());

在您自己的方法中包装Directory.GetDirectories(),并调用它,然后如果Directory.Exists()测试失败,您可以让它返回您想要的任何内容。谢谢!不得不为我的环境做一些调整,但效果与广告一样!谢谢您抽出时间;-)