fillthevoid
fillthevoid

Reputation: 21

How to create a folder and ask the user where to save it to in C#?

I think that all i need is in the question. I placed my method in my Form.Load I can either create a folder or open a SaveFileDialog but not both at once.

If someone could help me please. Thanks.

Upvotes: 1

Views: 204

Answers (3)

McAfeeJ
McAfeeJ

Reputation: 45

This would be to create a new directory

 Directory.CreateDirectory(@"C:\Your File Path Here");

This would be to open a file. You can select where it opens the initial directory of the file by changing the path.

 OpenFileDialog openFileDialog1 = new OpenFileDialog();
        openFileDialog1.InitialDirectory = (@"C:\Your starting File Path");
        openFileDialog1.Filter = "All Files (*.*)|*.*";
        openFileDialog1.Title = "Select a File";

Upvotes: 0

Eren Ersönmez
Eren Ersönmez

Reputation: 39085

SaveFileDialog lets the user choose a file location that already exists. If not, they can create a folder within the dialog as @Bali suggested.

If you want the user to be able to create a new folder without using the dialog then you'll need to let the user type the path (e.g. in a textbox). Then you can check to see if the directory exist using Directory.Exist, and if not, create it using Directory.Create.

void CheckPath(string path)
{
   var dir = Path.GetDirectoryName(path);
   if( !String.IsNullOrEmpty(dir) && !Directory.Exists(dir))
      Directory.Create(dir);
}

Upvotes: 1

kol
kol

Reputation: 28688

Open a FolderBrowserDialog for the user with the title (Description property) set to something like "Choose an existing folder or create a new one". Do not forget to set its ShowNewFolderButton property to true.

You can also use the FolderBrowserDialog to ask the user only to select the containing ("parent") folder, and create the new folder yourself by calling Directory.CreateDirectory. In this case, ShowNewFolderButton should be false.

Upvotes: 1

Related Questions