我在我的应用程序中使用FileUploader控件。我想保存一个文件到指定的文件夹。如果这个文件夹不存在,我想先创建它,然后将我的文件保存到这个文件夹。如果文件夹已经存在,那么只需将文件保存在其中。

我该怎么做呢?


当前回答

从多个答案衍生/组合而来,对我来说,实现它就像这样简单:

public void Init()
{
    String platypusDir = @"C:\platypus";
    CreateDirectoryIfDoesNotExist(platypusDir);
}

private void CreateDirectoryIfDoesNotExist(string dirName)
{
    System.IO.Directory.CreateDirectory(dirName);
}

其他回答

如果文件夹不在图像文件夹或其他文件夹下,请使用此代码

string subPath = HttpContext.Current.Server.MapPath(@"~/Images/RequisitionBarCode/");

bool exists = System.IO.Directory.Exists(subPath);
if(!exists)
    System.IO.Directory.CreateDirectory(subPath);

string path = HttpContext.Current.Server.MapPath(@"~/Images/RequisitionBarCode/" + OrderId + ".png");

如果路径还不存在,可以使用如下方法创建路径:

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);

下面的代码是我使用的最好的代码行,如果不存在,将创建目录。

System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath("~/temp/"));

如果目录已经存在,此方法不会创建新目录,但会返回现有目录的DirectoryInfo对象。>

创建一个新文件夹,给定父文件夹的路径:

        string pathToNewFolder = System.IO.Path.Combine(parentFolderPath, "NewSubFolder");
        DirectoryInfo directory = Directory.CreateDirectory(pathToNewFolder); 
       // Will create if does not already exist (otherwise will ignore)

指定新文件夹的路径 目录信息变量,因此您可以继续操作它,如您所愿。