本文介绍了创建文件,递归创建目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读C#的一些文件IO教程,并设法写出了一些文件,但是如果给出的路径包含目录怎么办?

I was reading some file IO tutorials for C# and have managed to write out some files, but what if the path I'm given contains directories?

例如,我要创建一个名为 data/my_file 的文件,但 data 文件夹不存在.

For example, I want to create the file called data/my_file except data folder doesn't exist.

行,

BinaryWriter outFile = new BinaryWriter(File.OpenWrite(path));

其中 path 是上面的字符串,崩溃并提示消息路径的一部分不存在,这意味着C#未能按要求创建它们.

where path is the above string, crashes with the message that part of the path doesn't exist, which means C# isn't creating them as required.

我希望C#处理所有混乱的目录创建并为我检查,而不是我必须解析路径并创建所有必要的目录.这可能吗?否则,是否存在一小段代码,我可以将其复制到项目中,以处理可能忽略的所有内容(因为我对文件管理了解不多).

I would like C# to handle all of the messy directory creation and checking for me instead of me having to parse the path and create all of the necessary directories. Is this possible? Otherwise, is there a snippet of code that I can just copy over into my project which will handle anything I might be overlooking (since I don't know much about file management).

推荐答案

将在指定路径中创建所有目录和子目录(如果它们不存在的话).

System.IO.Directory.CreateDirectory() will create all directories and subdirectories in a specified path, should they not already exist.

您可以通过传递路径来调用它,以确保在写入文件之前创建了文件夹结构.

You can call it, passing the path, to ensure the folder structure is created prior to writing your file.

这篇关于创建文件,递归创建目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-03 19:04