如果创建文件不存在,如何创建目录? [英] How do I create directory if it doesn't exist to create a file?

查看:27
本文介绍了如果创建文件不存在,如何创建目录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a piece of code here that breaks if the directory doesn't exist:

System.IO.File.WriteAllText(filePath, content);

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

In one line (or a few lines), is it possible to check if the directory leading to the new file doesn't exist and if not, to create it before creating the new file?

我使用的是 .NET 3.5.

I'm using .NET 3.5.

推荐答案

创建

(new FileInfo(filePath)).Directory.Create() 在写入文件之前.

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

这篇关于如果创建文件不存在,如何创建目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆