1

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?

enter image description here

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?

Community
  • 1
  • 1
sazr
  • 24,984
  • 66
  • 194
  • 362
  • Your question is the same as the one you've linked to, but you're using your full filename instead of the folder name. – Dan Puzey Jun 25 '14 at 05:36
  • 1
    In fairness, the question is a duplicate of the marked one, but the OP is correct in complaining that the accepted answer doesn't address their issue. – Douglas Jun 25 '14 at 05:41
  • On second thoughts, I've reopened. The *title* of the question is a duplicate; the question itself is clearly a follow-up on the accepted answer from the other one. – Douglas Jun 25 '14 at 05:52

1 Answers1

6

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
Douglas
  • 53,759
  • 13
  • 140
  • 188