2012-11-21 34 views

回答

3

你可能希望創建文件夾後,你可以使用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); 
    } 
} 
0

詳情:有兩個不同的密鑰目錄路徑和文件,使其更容易

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"); 
    } 
    } 
1

你的問題不是很清楚,但我假設你想要做這樣的事情

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)) 
{ 

} 
相關問題