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

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

问题描述

我有一张code在这里打破,如果目录不存在:

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.

推荐答案

(新的FileInfo(文件路径))。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天全站免登陆