【问题标题】:C# Dynamically Map File System Using RecursionC# 使用递归动态映射文件系统
【发布时间】:2017-03-09 04:35:30
【问题描述】:

我正在尝试使用 C# 将文件夹结构动态映射为 JSON 格式。

这是我的方法:

public static string StartJson(string Dir)
{
    try
    {
        StringBuilder Json = new StringBuilder();
        Json.Append("{\"FileSystem\" : [");
        if (Directory.GetDirectories(Dir).ToList().Count > 0)
        {
            Json.Append(GetDirectoryJson(Dir, 0));
        }

        if(Directory.GetFiles(Dir).ToList().Count > 0 && Directory.GetDirectories(Dir).ToList().Count == 0)
        {
            Json.Append(GetFileJSON(Dir));
        }
        else if(Directory.GetFiles(Dir).ToList().Count > 0 && Directory.GetDirectories(Dir).ToList().Count > 0)
        {
            Json.Append(",");
            Json.Append("{");
            Json.Append(GetFileJSON(Dir));
            Json.Append("}");
        }
        Json.Append("]}");//Close FileSystem
        return Json.ToString();
    }
    catch(Exception e) { return ""; }
}
public static int count = 0;
public static string GetDirectoryJson(string Dir, int Iteration)
{
    try
    {
        string path1 = Directory.GetParent(Dir).FullName;
        bool p = path.Equals(Directory.GetParent(Dir).FullName);
        StringBuilder Json = new StringBuilder();
        int folders = Directory.GetDirectories(path).ToList().Count;    
        foreach (string DirectoryPath in Directory.GetDirectories(Dir))
        {

            Json.Append("{");
            Json.Append("\"Folder\": [{");
            Json.Append("\"FolderPath\": " + "\"" + DirectoryPath.Replace('\\', '/') + "\"");
            if(Directory.GetDirectories(DirectoryPath).ToList().Count > 0)
            {
                Json.Append(",");
                Json.Append("\"Sub\": [");
                count++;
                Json.Append(GetDirectoryJson(DirectoryPath, Iteration++));
                Json.Append("]");
            }


            if (Directory.GetFiles(DirectoryPath).ToList().Count > 0)
            {
                Json.Append(",");
                Json.Append(GetFileJSON(Dir));
            }
            Json.Append("}");
            Json.Append("]");
            Json.Append("}");
        }
        return Json.ToString();
    }
    catch (Exception e) { return "Fail"; }
}

public static string GetFileJSON(string Dir)
{
    try
    {
        StringBuilder Json = new StringBuilder();
        Json.Append("\"Files\": [");
        int FileCount = 0;
        foreach (string FilePath in Directory.GetFiles(Dir))
        {
            Json.Append("{\"FilePath\": " + "\"" + FilePath.Replace('\\', '/') + "\"");
            FileCount++;
            if (Directory.GetFiles(Dir).ToList().Count == FileCount)
                Json.Append("}");
            else
                Json.Append("},");
        }
        Json.Append("]");

        return Json.ToString();
    }
    catch(Exception e) { return ""; }
}

我已经非常接近了,因为当我使用我的测试文件夹时,这会输出大多数正确的 JSON:"C:\Users\sredmond.QPS_DOMAIN\Documents\Test" 我得到以下 JSON:

{  
   "FileSystem":[  
      {  
         "Folder":[  
            {  
               "FolderPath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/Sub1",
               "Sub":[  
                  {  
                     "Folder":[  
                        {  
                           "FolderPath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/Sub1/CantLogin_files",
                           "Sub":[  
                              {  
                                 "Folder":[  
                                    {  
                                       "FolderPath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/Sub1/CantLogin_files/images",
                                       "Files":[  
                                          {  
                                             "FilePath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/Sub1/CantLogin_files/CheckBrowser.js.download"
                                          },
                                          {  
                                             "FilePath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/Sub1/CantLogin_files/footer_right.jpg"
                                          },
                                          {  
                                             "FilePath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/Sub1/CantLogin_files/ga.js.download"
                                          },
                                          {  
                                             "FilePath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/Sub1/CantLogin_files/igpnl_up.gif"
                                          },
                                          {  
                                             "FilePath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/Sub1/CantLogin_files/ig_panel.css"
                                          },
                                          {  
                                             "FilePath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/Sub1/CantLogin_files/ig_shared.css"
                                          },
                                          {  
                                             "FilePath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/Sub1/CantLogin_files/jquery-1.9.0.min.js.download"
                                          },
                                          {  
                                             "FilePath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/Sub1/CantLogin_files/jquery.browser.js.download"
                                          },
                                          {  
                                             "FilePath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/Sub1/CantLogin_files/jquery.cookie.js.download"
                                          },
                                          {  
                                             "FilePath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/Sub1/CantLogin_files/qps_logo.png"
                                          },
                                          {  
                                             "FilePath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/Sub1/CantLogin_files/QPS_New.css"
                                          },
                                          {  
                                             "FilePath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/Sub1/CantLogin_files/ScriptResource(1).axd"
                                          },
                                          {  
                                             "FilePath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/Sub1/CantLogin_files/ScriptResource(2).axd"
                                          },
                                          {  
                                             "FilePath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/Sub1/CantLogin_files/ScriptResource(3).axd"
                                          },
                                          {  
                                             "FilePath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/Sub1/CantLogin_files/ScriptResource(4).axd"
                                          },
                                          {  
                                             "FilePath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/Sub1/CantLogin_files/ScriptResource.axd"
                                          },
                                          {  
                                             "FilePath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/Sub1/CantLogin_files/secondaryNavBG_right.jpg"
                                          },
                                          {  
                                             "FilePath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/Sub1/CantLogin_files/WebResource.axd"
                                          }
                                       ]
                                    }
                                 ]
                              }
                           ],
                           "Files":[  
                              {  
                                 "FilePath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/Sub1/CantLogin.html"
                              },
                              {  
                                 "FilePath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/Sub1/UsersAndPass.csv"
                              }
                           ]
                        }
                     ]
                  }
               ],
               "Files":[  
                  {  
                     "FilePath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/New Hire Reporting Form - Copy.pdf"
                  },
                  {  
                     "FilePath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/New Hire Reporting Form.pdf"
                  }
               ]
            }
         ]
      }      {  
         "Folder":[  
            {  
               "FolderPath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/Sub2",
               "Sub":[  
                  {  
                     "Folder":[  
                        {  
                           "FolderPath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/Sub2/Test",
                           "Files":[  
                              {  
                                 "FilePath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/Sub2/UsersAndPass - Big (737).csv"
                              }
                           ]
                        }
                     ]
                  }
               ],
               "Files":[  
                  {  
                     "FilePath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/New Hire Reporting Form - Copy.pdf"
                  },
                  {  
                     "FilePath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/New Hire Reporting Form.pdf"
                  }
               ]
            }
         ]
      }      {  
         "Folder":[  
            {  
               "FolderPath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/Sub3"
            }
         ]
      },
      {  
         "Files":[  
            {  
               "FilePath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/New Hire Reporting Form - Copy.pdf"
            },
            {  
               "FilePath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/New Hire Reporting Form.pdf"
            }
         ]
      }
   ]
}

如您所见,JSON 几乎是正确的,但没有逗号分隔在根目录下找到的文件夹。您可以将 JSON 放在此处:https://jsonformatter.curiousconcept.com/ 并亲自查看错误发生在哪里。

无论如何,我的问题是如何做到这一点,以便将这些逗号放在正确的位置。每次我尝试添加逗号或在其中添加条件时,都会将逗号放在 JSON 中的随机位置。

【问题讨论】:

  • 与其从头开始编写 json 为什么不创建树视图然后使用 json.net 解析^
  • 如何获得树状视图?
  • 我会展示,只需两分钟
  • 啊,我应该提到这是一个 WebService,它应该返回一个 JSON 对象供 JavaScript 解析并创建文件夹视图
  • 无论出于什么目的,您通常都不应该自己操作或构建 JSON text。相反,构建一个表示数据的类结构,填写数据结构的一个实例,然后使用 Json.Net 之类的库从数据构建 JSON。

标签: c# json recursion


【解决方案1】:

问题隐藏在 GetDirectoryJson 最后Json.Append("}") 您需要在同一级别的目录之间添加逗号。如果目录树更宽,您会看到更多逗号问题。

话虽如此,正如建议的那样,您最好使用一个已经被许多人测试和使用的完善的库,例如JSON.Net

【讨论】:

    【解决方案2】:

    谢谢大家的回复。在深入研究 JSON.NET 之后,我在这里找到了一个很好的答案:Is there a way to directly get a directory structure and parse it to Json in C#?

    【讨论】:

      【解决方案3】:

      不要通过字符串操作创建json...

      我会创建一个自定义类文件夹并使用递归方法

      public class Folder
      {
          public string Path { set; get; }
          public List<string> Files { set; get; }
          public List<Folder> SubFolders { set; get; }
      
      }
      
      Folder GetFolderHierarchy(string root)
      {
          var folder = new Folder();
          var dir = new DirectoryInfo(root);
      
          folder.Path = root;
          folder.Files =  dir.GetFiles().Select(x => x.FullName).ToList();
      
          folder.SubFolders = dir.GetDirectories().Select(x => GetFolderHierarchy(x.FullName))
                              .ToList();
      
          return folder;
      
      }
      

      现在,你可以称它为

      var folder = GetFolderHierarchy(@"d:\temp");
      var json = JsonConvert.SerializeObject(folder, Newtonsoft.Json.Formatting.Indented);
      

      添加

      如果你想存储相对路径而不是完整路径,方法可以更改为:

      Folder GetFolderHierarchy(string root)
      {
          var folder = new Folder();
          var dir = new DirectoryInfo(root);
      
      
          folder.Files = dir.GetFiles().Select(x => x.Name).ToList();
          folder.Path = dir.Name;
          folder.SubFolders = dir.GetDirectories().Select(x => GetFolderHierarchy(x.FullName))
                              .ToList();
      
          return folder;
      }
      

      【讨论】:

        猜你喜欢
        • 2011-02-03
        • 1970-01-01
        • 2011-07-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-07-24
        • 1970-01-01
        • 2013-10-31
        相关资源
        最近更新 更多