C# 保存文件并自动创建目录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/660685/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 12:18:30  来源:igfitidea点击:

Saving a file and automatically create directories

c#winformsfile

提问by leora

I am concatenating a number of variables and I want to save that string as a file path.

我连接了许多变量,我想将该字符串保存为文件路径。

Is there a way it will automatically create all appropriate directories if they don't exist without having to check "if exists" on each one

有没有一种方法,如果它们不存在,它会自动创建所有适当的目录,而不必检查每个目录的“是否存在”

For example.

例如。

"C:\" + a + "\" + b+ "\" + d + "\" + d + ".txt"

采纳答案by Jon Skeet

Use new FileInfo(path).Directory.Create().

使用new FileInfo(path).Directory.Create().

(This creates anything in the hierarchy that's required. If the directory already exists it does nothing.)

(这会在层次结构中创建所需的任何内容。如果目录已经存在,则它什么都不做。)

回答by shahkalpesh


using System.IO;
....
Directory.CreateDirectory(@"c:\temp\a\b\c\d\e");