我正在創建一個c#應用程序,該應用程序在app.config中有一個文件路徑,如果它存在/不存在,我想創建或覆蓋它。如何爲可能不存在的路徑和文件創建完整的目錄結構?
例子:<add key="file" value="c:\myapp\file.txt"/>
我有問題與目錄/文件組合創建。
可有人請給我如何創建整個文件夾路徑包括一個空的文本文件
我正在創建一個c#應用程序,該應用程序在app.config中有一個文件路徑,如果它存在/不存在,我想創建或覆蓋它。如何爲可能不存在的路徑和文件創建完整的目錄結構?
例子:<add key="file" value="c:\myapp\file.txt"/>
我有問題與目錄/文件組合創建。
可有人請給我如何創建整個文件夾路徑包括一個空的文本文件
你可能希望創建文件夾後,你可以使用FileStream只寫文件的代碼示例。
我有一個方便的函數,可以在寫入目錄中的文件之前創建該目錄,該文件可能不存在。
/// <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);
if (!System.IO.Directory.Exists(folder)) {
System.IO.Directory.CreateDirectory(folder);
}
}
詳情:有兩個不同的密鑰目錄路徑和文件,使其更容易
App.Config中
<add key="filePath" value="c:\myapp\"/>
<add key="fileName" value="file.txt"/>
類
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");
}
}
你的問題不是很清楚,但我假設你想要做這樣的事情
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))
{
}