[英]How to Create A File Even If Sub-Directories Dont Exist
How can I create a file even if the some sub-directories dont exist? 即使某些子目录不存在,如何创建文件? I am aware of this Question and its answer that suggests I use
Directory.CreateDirectory(path)
to create both my file and its directories. 我知道这个问题及其答案 ,这表明我使用
Directory.CreateDirectory(path)
来创建我的文件及其目录。
But when I attempt to create my file using Directory.CreateDirectory(path)
it creates the file as a directory/folder and not as a file? 但是,当我尝试使用
Directory.CreateDirectory(path)
创建文件时,会将文件创建为目录/文件夹而不是文件吗?
Directory.CreateDirectory (@"C:\Users\me\AppData\LocalLow\company\product\database.db");
Why is database.db
a folder and not a file? 为什么
database.db
是文件夹而不是文件? Am I doing something wrong? 难道我做错了什么? How can I create a file even if the some sub-directories dont exist?
即使某些子目录不存在,如何创建文件?
You need to specify the directory path to the CreateDirectory
method, not the full file path. 您需要指定
CreateDirectory
方法的目录路径,而不是完整的文件路径。 You can extract this from the full path using GetDirectoryName
: 您可以使用
GetDirectoryName
从完整路径中提取出来:
string filePath = @"C:\Users\me\AppData\LocalLow\company\product\database.db";
string dirPath = Path.GetDirectoryName(filePath);
// gives @"C:\Users\me\AppData\LocalLow\company\product"
Directory.CreateDirectory(dirPath);
File.Create(filePath); // can use any file API call here, such as File.Open
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.