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

我该怎么做呢?


当前回答

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

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

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

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

如果该文件夹不存在,该方法将创建该文件夹,如果存在则不执行任何操作:

Directory.CreateDirectory(path);

使用System.IO.Directory.CreateDirectory。


据该官员说。NET"文档,你不需要先检查它是否存在。

系统。io >目录>目录。CreateDirectory path中指定的任何和所有目录都将被创建,除非它们已经存在或path的某些部分无效。如果目录已经存在,此方法不会创建新目录,但会返回现有目录的DirectoryInfo对象。         — learn.microsoft.com/dotnet/api/


就写这一行:

System.IO.Directory.CreateDirectory("my folder");

如果该文件夹还不存在,则将创建该文件夹。 如果文件夹已经存在,那么该行将被忽略。

参考:关于目录的文章。在MSDN创建目录

当然,你也可以使用System.IO;在源文件的顶部,然后只写目录。CreateDirectory(“我的文件夹”);每次你想创建一个文件夹。