我在我的应用程序中使用FileUploader控件。我想保存一个文件到指定的文件夹。如果这个文件夹不存在,我想先创建它,然后将我的文件保存到这个文件夹。如果文件夹已经存在,那么只需将文件保存在其中。
我该怎么做呢?
我在我的应用程序中使用FileUploader控件。我想保存一个文件到指定的文件夹。如果这个文件夹不存在,我想先创建它,然后将我的文件保存到这个文件夹。如果文件夹已经存在,那么只需将文件保存在其中。
我该怎么做呢?
当前回答
你可以使用try/catch子句来检查它是否存在:
try
{
if (!Directory.Exists(path))
{
// Try to create the directory.
DirectoryInfo di = Directory.CreateDirectory(path);
}
}
catch (IOException ioex)
{
Console.WriteLine(ioex.Message);
}
其他回答
string root = @"C:\Temp";
string subdir = @"C:\Temp\Mahesh";
// If directory does not exist, create it.
if (!Directory.Exists(root))
{
Directory.CreateDirectory(root);
}
CreateDirectory还用于创建子目录。您所要做的就是指定将在其中创建该子目录的目录的路径。下面的代码片段在C:\Temp目录中创建了一个Mahesh子目录。
// Create sub directory
if (!Directory.Exists(subdir))
{
Directory.CreateDirectory(subdir);
}
从多个答案衍生/组合而来,对我来说,实现它就像这样简单:
public void Init()
{
String platypusDir = @"C:\platypus";
CreateDirectoryIfDoesNotExist(platypusDir);
}
private void CreateDirectoryIfDoesNotExist(string dirName)
{
System.IO.Directory.CreateDirectory(dirName);
}
目录中。CreateDirectory解释了如果FilePath不存在,如何尝试创建FilePath。
目录中。Exists命令用于检查FilePath是否存在。但是,您不需要这样做,因为CreateDirectory将为您检查它。
如果路径还不存在,可以使用如下方法创建路径:
using System.IO;
private void CreateIfMissing(string path)
{
bool folderExists = Directory.Exists(Server.MapPath(path));
if (!folderExists)
Directory.CreateDirectory(Server.MapPath(path));
}
如果该文件夹不存在,该方法将创建该文件夹,如果存在则不执行任何操作:
Directory.CreateDirectory(path);