简体   繁体   中英

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.

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 (@"C:\Users\me\AppData\LocalLow\company\product\database.db");

Why is database.db a folder and not a file? 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. You can extract this from the full path using 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM