Search code examples
c#directorysubdirectory

How to create a Sub Folder into an existing folder?


When my Windows Form Loads it run the following code Directory.CreateDirectory(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "F.U.T.U.R.E")); Which therefor create a folder with the name "F.U.T.U.R.E" Inside MyDocuments Directory. Now I would like to create another Folder when I press on a button inside the existing folder "F.U.T.U.R.E" .

private void button1_Click(object sender, EventArgs e)
{
  // Create Sub Folder into My.Documents."F.U.T.U.R.E"
}

Can anyone help me with the codes.


Solution

  • Well, one way is to use the DirectoryInfo that gets returned from that original CreateDirectory call, and use the CreateSubdirectory method on it to do as needed.

    https://msdn.microsoft.com/en-us/library/system.io.directoryinfo(v=vs.110).aspx

    So:

    var directoryInfo = Directory.CreateDirectory(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "F.U.T.U.R.E"));
    
    directoryInfo.CreateSubdirectory("MySubFolder");
    

    However, there are a fair few ways to achieve this so don't take this as the defacto way to do it. Personally I never even realised the CreateSubdirectory method even existed, I've always done it by building the URLs and calling the CreateDirectory method. Learn something new everyday :-)