user1526912
user1526912

Reputation: 17230

How do I create an entire directory structure for a perhaps nonexistant path and file?

I am working on a c# application that has a file path in the app.config that I would like to create or overwrite if it does/doesn't exist.

Example: <add key="file" value="c:\myapp\file.txt"/>

I am having problems with the directory / file combination creation.

Can someone please give me code example of how to create the entire folder path including an empty text file

Upvotes: 1

Views: 10722

Answers (3)

Zyo
Zyo

Reputation: 2068

Your probably looking to create the folder, after that you can just write the file using a FileStream.

I have handy function that create the directory before writing to a file in a directory that may not exist.

/// <summary>
/// Create the folder if not existing for a full file name
/// </summary>
/// <param name="filename">full path of the file</param>
public static void CreateFolderIfNeeded(string filename) {
  string folder = System.IO.Path.GetDirectoryName(filename);
  System.IO.Directory.CreateDirectory(folder);
}

Upvotes: 5

MVCKarl
MVCKarl

Reputation: 1295

Details: Have the directory Path and File in two different keys to make it easier

App.Config

<add key="filePath" value="c:\myapp\"/>
<add key="fileName" value="file.txt"/>


Class

string path = ConfigurationManager.AppSettings["filePath"];
string fileName = ConfigurationManager.AppSettings["fileName"];
string currentPathAndFile = path + fileName;

 if (!File.Exists(currentPathAndFile)) // Does the File and Path exist
 {
    if (!Directory.Exists(path))  // Does the directory exist
      Directory.CreateDirectory(path);

     // Create a file to write to. 
     using (StreamWriter sw = File.CreateText(currentPathAndFile)) 
     {
         sw.WriteLine("Hello");
         sw.WriteLine("And");
         sw.WriteLine("Welcome");
     }  
  }

Upvotes: 0

codingbiz
codingbiz

Reputation: 26386

Your question is not quite clear, but I am assuming you want to do something like this

using System.IO;
...

string path = ConfigurationManager.AppSettings["FolderPath"];
string fullPath = Path.Combine(path, "filename.txt");

if(!Directory.Exists(path))
{
   Directory.CreateDirectory(path);
}

using(StreamWriter wr = new StreamWriter(fullPath, FileMode.Create))
{

}

Upvotes: 2

Related Questions