How can I create a new开发者_JS百科 folder in asp.net using c#?
var folder = Server.MapPath("~/App_Data/uploads/random");
if (!Directory.Exists(folder))
{
Directory.CreateDirectory(folder);
}
path
is the variable holding the directory name
Directory.CreateDirectory(path);
You can read more about it here
Directory.CreateDirectory. However you will have to make sure the application pool user has rights to create the directory.
if (!Directory.Exists(Path))
{
Directory.CreateDirectory(Path);
}
try this, for a better one.
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);
Directory.CreateDirectory(Server.MapPath(folderPath));
There is no need to check if folder exists, because if it exists method CreateDirectory does nothing.
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");
}
精彩评论