string pathToNewFolder = System.IO.Path.Combine(parentFolderPath, "NewSubFolder");
DirectoryInfo directory = Directory.CreateDirectory(pathToNewFolder);
// Will create if does not already exist (otherwise will ignore)
给出新文件夹的
路径
目录信息变量,以便您可以随意继续操作它 .
1
using System.IO
if (!Directory.Exists(yourDirectory))
Directory.CreateDirectory(yourDirectory);
-2
if (!Directory.Exists(Path.GetDirectoryName(fileName)))
{
Directory.CreateDirectory(Path.GetDirectoryName(fileName));
}
string fileToCopy = "filelocation\\file_name.txt";
String server = Environment.UserName;
string newLocation = "C:\\Users\\" + server + "\\Pictures\\Tenders\\file_name.txt";
string folderLocation = "C:\\Users\\" + server + "\\Pictures\\Tenders\\";
bool exists = System.IO.Directory.Exists(folderLocation);
if (!exists)
{
System.IO.Directory.CreateDirectory(folderLocation);
if (System.IO.File.Exists(fileToCopy))
{
MessageBox.Show("file copied");
System.IO.File.Copy(fileToCopy, newLocation, true);
}
else
{
MessageBox.Show("no such files");
}
}
5
如果路径尚不存在,则可以使用如下方法创建路径:
using System.IO;
private void CreateIfMissing(string path)
{
bool folderExists = Directory.Exists(Server.MapPath(path));
if (!folderExists)
Directory.CreateDirectory(Server.MapPath(path));
}
-4
string root = @"C:\Temp";
string subdir = @"C:\Temp\Mahesh";
// If directory does not exist, create it.
if (!Directory.Exists(root))
{
Directory.CreateDirectory(root);
}
15 回答
如果不存在,此方法将创建文件夹,如果存在则不执行任何操作
正如其他人所说,使用
System.IO.Directory.CreateDirectory
但是,您不需要先检查它是否存在 . 来自docs
您可以使用try / catch子句并检查它是否存在:
以下代码是我使用的最佳代码行,如果不存在则将创建目录 .
如果该目录已存在,则此方法不会创建新目录,但会返回现有目录的DirectoryInfo对象 . >
从多个答案派生/组合,为我实现它就像这样简单:
这是我正在寻找的答案,但并不容易找到:
给出新文件夹的
路径
目录信息变量,以便您可以随意继续操作它 .
Directory.Exists这将解释如何检查FilePath是否存在
Directory.CreateDirectory这将解释如何尝试创建FilePath(如果它不存在)
根据http://forums.asp.net/p/1226236/2209871.aspx使用以下代码:
只需写下这一行:
如果文件夹为 not exist yet ,则为 created .
如果文件夹 exists already ,该行将为 ignored .
参考:Article about Directory.CreateDirectory at MSDN
使用下面的代码 . 我使用此代码进行文件复制并创建新文件夹 .
如果路径尚不存在,则可以使用如下方法创建路径:
CreateDirectory还用于创建子目录 . 您所要做的就是指定将在其中创建此子目录的目录的路径 . 以下代码段在
C:\Temp directory
中创建Mahesh子目录 .