创建空文件夹结构的最干净方法

时间:2018-10-22 06:33:45

标签: c# file-io directory-structure

我对C#相当陌生(但很有动力),所以请耐心等待。目前,我正在直接在Grasshopper中使用C#进行编码(稍后,我可能会将其移出并用VS编写,但暂时不行)。我想创建一个文件夹结构,其中包含一些空文件夹和一些包含文本文件的文件夹,稍后我要写这些文件。

因此,在Google的帮助下,我设法做到了这一点,但我不相信这是最好/最清洁/最有效的方法。

有人可以在这里给我一些批评吗:)

欢呼声, 大卫。

string folderPath = @"C:\Users\David\Desktop\Folder";

string firstSubFolderPath = System.IO.Path.Combine(folderPath, "firstSubFolder");
string secondSubFolderPath = System.IO.Path.Combine(folderPath, "secondSubFolder");

System.IO.Directory.CreateDirectory(firstSubFolderPath);
System.IO.Directory.CreateDirectory(secondSubFolderPath);

string subSubFolderPath = System.IO.Path.Combine(firstSubFolderPath, "subSubFolder");
System.IO.Directory.CreateDirectory(subSubFolderPath);
string firstTextFile = "firstTextFile.txt";
string secondTextFile = "secondTextFile.txt";

firstTextFile= System.IO.Path.Combine(subSubFolderPath, firstTextFile);
secondTextFile= System.IO.Path.Combine(secondSubFolderPath, secondTextFile);

using (StreamWriter firstWriter = new StreamWriter(firstTextFile));
using (StreamWriter secondWriter = new StreamWriter(secondTextFile));

1 个答案:

答案 0 :(得分:2)

如果您使用DirectoryInfo类,则可以使用一种流利的语法,它可能更易读。

此代码创建第一个文件夹及其子文件夹,并返回其路径,然后您可以使用该路径来创建文本文件。

    var folderPath = @"C:\Users\David\Desktop\Folder";

    var subsubfolder = new DirectoryInfo(folderPath)
        .CreateSubdirectory("subfolder")
        .CreateSubdirectory("subsubfolder")
        .FullName;