25

How can I create a new folder in asp.net using c#?

0

7 Answers 7

39
var folder = Server.MapPath("~/App_Data/uploads/random");
if (!Directory.Exists(folder))
{
    Directory.CreateDirectory(folder);
}
Sign up to request clarification or add additional context in comments.

1 Comment

This should be the accepted answer, you need to use Server.MapPath.
20

path is the variable holding the directory name

Directory.CreateDirectory(path);

You can read more about it here

Comments

8

Directory.CreateDirectory. However you will have to make sure the application pool user has rights to create the directory.

Comments

7
if (!Directory.Exists(Path)) 
{
    Directory.CreateDirectory(Path);
}

try this, for a better one.

Comments

5

First, remember that the directory will appear on the server, not the client. You also have to have the rights to create the folder. Finally, in a load balanced environment the folder will appear only on the server that created it, it won't be replicated unless there is some background service that does that for you.

using System.IO;

Directory.CreateDirectory(folderPath);

Comments

4
Directory.CreateDirectory(Server.MapPath(folderPath));

There is no need to check if folder exists, because if it exists method CreateDirectory does nothing.

1 Comment

That was the point i am looking for. What if the folder already exists. Thank you for mentioning that.
3

Most people will say Directory.CreateDirectory(path) so I'll provide an alternative:

DirectoryInfo.CreateSubdirectory(name)

The DirectoryInfo object will give you access to a decent amount of information about the parent directory in case there are conditions for creating the subdirectory (like checking if the parent actually exists or not). Perhaps something like:

var directoryInfo = new DirectoryInfo("C:\\Path\\To\\Parent\\");

if(directoryInfo.Exists)
{
    directoryInfo.CreateSubdirectory("NewFolder");
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.