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

我该怎么做呢?


当前回答

使用System.IO.Directory.CreateDirectory。


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

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


其他回答

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

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

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

使用下面的代码按如何使用文件上传服务器控件动态创建文件夹?:

string subPath ="ImagesPath"; // Your code goes here

bool exists = System.IO.Directory.Exists(Server.MapPath(subPath));

if(!exists)
    System.IO.Directory.CreateDirectory(Server.MapPath(subPath));

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

Directory.CreateDirectory(path);
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);

}

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

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