David Andersson
David Andersson

Reputation: 31

The cleanest way of creating an empty folder structure

I'm fairly new to C# (but very motivated) so please bear with me. I'm coding in C# directly in Grasshopper at the moment (later on I will probably move it out of there and write in VS, but not for now). I want to create a folder structure with some empty folders and some folders with text files, which I later on want to write to.

So with help of Google I managed to do this but I'm not convinced that this is the best/cleanest/most efficient way of doing this.

Could someone give me some critic here please :)

cheers, David.

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

Upvotes: 0

Views: 1536

Answers (1)

John Wu
John Wu

Reputation: 52250

If you use the DirectoryInfo class, you can use a sort of fluent syntax, which may be more readible.

This code creates the first folder and its subfolder and returns its path, which you can then use to create the text files.

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

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

Upvotes: 2

Related Questions