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

我该怎么做呢?


当前回答

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

using System.IO;

private void CreateIfMissing(string path)
{
  bool folderExists = Directory.Exists(Server.MapPath(path));
  if (!folderExists)
    Directory.CreateDirectory(Server.MapPath(path));
}

其他回答

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

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

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

一种奇特的方法是使用您想要的方法扩展FileUpload。

添加:

public static class FileUploadExtension
{
    public static void SaveAs(this FileUpload, string destination, bool autoCreateDirectory) { 

        if (autoCreateDirectory)
        {
            var destinationDirectory = new DirectoryInfo(Path.GetDirectoryName(destination));

            if (!destinationDirectory.Exists)
                destinationDirectory.Create();
        }

        file.SaveAs(destination);
    }
}

然后使用它:

FileUpload file;
...
file.SaveAs(path,true);

你可以使用try/catch子句来检查它是否存在:

  try
  {
    if (!Directory.Exists(path))
    {
       // Try to create the directory.
       DirectoryInfo di = Directory.CreateDirectory(path);
    }
  }
  catch (IOException ioex)
  {
     Console.WriteLine(ioex.Message);
  }
if (!Directory.Exists(Path.GetDirectoryName(fileName)))
{
    Directory.CreateDirectory(Path.GetDirectoryName(fileName));
}

目录中。CreateDirectory解释了如果FilePath不存在,如何尝试创建FilePath。

目录中。Exists命令用于检查FilePath是否存在。但是,您不需要这样做,因为CreateDirectory将为您检查它。