Dot-Net

從路徑創建文件,如果不存在則創建子目錄

  • January 24, 2019

在我的應用程序的配置中,我有一個路徑,例如“logs\updater\updater.log”

啟動應用程序,我想創建文件 updater.log,如果不存在則創建所有子文件夾。

因此,如果明天我的使用者將配置中的路徑更改為“logs\mypathisbetter\updater.log”,我的應用程序將繼續工作,將日誌寫入新文件。

File.Create, FileInfo.Create,Streamwriter.Create左右:他們這樣做?

還是我需要檢查文件夾是否存在?

我在網上找不到這個問題的明確答案。

使用一點程式碼解決:

private static void EnsureDirectoryExists(string filePath) 
{ 
 FileInfo fi = new FileInfo(filePath);
 if (!fi.Directory.Exists) 
 { 
   System.IO.Directory.CreateDirectory(fi.DirectoryName); 
 } 
}

對不起,這個真正的新手文章……謝謝大家!:-)

不,他們似乎沒有 - 你會得到一個 DirectoryNotFoundException,我相信來自這三個。

你需要做一些類似Directory.CreateDirectory(path)第一次的事情。

編輯

對於以包含文件名的路徑開頭的完整解決方案,請嘗試:

   Directory.CreateDirectory(Path.GetDirectoryName(fullPath));

   TextWriter writer = new StreamWriter(fullPath);
   writer.WriteLine("hello mum");
   writer.Close();

但請記住,您還需要一些錯誤處理,以便編寫器始終關閉(在“finally”塊中)。

引用自:https://stackoverflow.com/questions/3814364