Reputation: 17230
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
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
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
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