如果创建目录不存在,如何创建目录?

Dis*_*ive 190 .net c# file-io

如果目录不存在,我在这里有一段代码会中断:

System.IO.File.WriteAllText(filePath, content);
Run Code Online (Sandbox Code Playgroud)

在一行(或几行)中,是否可以检查导致新文件的目录是否不存在,如果不存在,是否可以在创建新文件之前创建它?

我正在使用.NET 3.5.

Don*_*Don 373

To Create

(new FileInfo(filePath)).Directory.Create() Before writing to the file.

....Or, If it exists, then create (else do nothing)

System.IO.FileInfo file = new System.IO.FileInfo(filePath);
file.Directory.Create(); // If the directory already exists, this method does nothing.
System.IO.File.WriteAllText(file.FullName, content);
Run Code Online (Sandbox Code Playgroud)

  • 优雅的解决方案,因为它处理需要创建嵌套文件夹的情况. (4认同)

Ram*_*Ram 103

You can use following code

  DirectoryInfo di = Directory.CreateDirectory(path);
Run Code Online (Sandbox Code Playgroud)

  • `Directory.CreateDirectory`完全符合您的要求:如果目录尚不存在,它会创建目录.**首先不需要进行明确的检查**. (41认同)
  • 如果`path`是文件而不是目录,则抛出IOException.https://msdn.microsoft.com/en-us/library/54a0at6s(v=vs.110).aspx (12认同)

wil*_*lvv 31

As @hitec said, you have to be sure that you have the right permissions, if you do, you can use this line to ensure the existence of the directory:

Directory.CreateDirectory(Path.GetDirectoryName(filePath))