简体   繁体   English

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

[英]C# Linq to XML Checking If Directory Exists

I have the following XML file layout: 我有以下XML文件布局:

<TopNode>
  <AppRun Date="26-Jun-17 02:15">
    <Folder Name="Folder1">
      <SubFolder Name="SubFolder1" />
      <SubFolder Name="SubFolder2" />
    </Folder>
    <Folder Name="Folder2">
      <SubFolder Name="SubFolder1" />
      <SubFolder Name="SubFolder2" />
    </Folder>
  </AppRun>
</TopNode>

And the following frankencode i've mashed together: 我将以下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))))))));

So I have the folder element names in an array as they stay constant; 所以我将文件夹元素名称保持在数组中,因为它们保持不变; However, the folders may not always be there. 但是,文件夹可能并不总是在那里。 So when the application tries to do the directories, it'll throw a DirectoryNotFound exception. 因此,当应用程序尝试执行目录时,它将引发DirectoryNotFound异常。 I'd like to keep an empty folder element in the xml even if the directory doesn't exist. 即使目录不存在,我也想在xml中保留一个空的文件夹元素。

Can someone point me in the right direction to edit this block of code to check the directory exists before trying to probe it. 有人可以指出正确的方向来编辑此代码块,以在尝试探查之前检查目录是否存在。

This will get all the SubFolders in you folders list 这将在您的文件夹列表中获得所有子文件夹

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM