2016-11-04 102 views
0

我想知道如何通過C#創建在窗口服務日誌事件文件的新目錄的新目錄創建日誌事件文件在Windows服務在C#

我有以下代碼:

public static void WriteLog(string Message) 
{ 
    StreamWriter sw = null; 
    try 
    { 
     sw = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "\\DataFile.txt", true); 
     //sw = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "C:\\MulpuriServiceLOG\\data.txt", true); 

     //sw.WriteLine(DateTime.Now.ToString() + ": " + Message); 
     sw.WriteLine(Message); 
     sw.Flush(); 
     sw.Close(); 
    } 
    catch{} 
} 
+1

希望你應該閱讀這個http://stackoverflow.com/help/how-to-ask –

回答

0
File yourFolder= new File("C:/yourFolder"); 

    // if the directory does not exist, create it 
    if (!yourFolder.exists()) { 
     System.out.println("Creando directorio: " + yourFolder.getName()); 
     boolean result = false; 

     try 
     { 
      yourFolder.mkdir(); 
      result = true; 
     } 
     catch(SecurityException se){ 

     }   
     if(result) {  
      System.out.println("Folder created"); 
     } 
    } 
+0

我想這是java代碼? OP要求提供C#代碼。 – TheRealVira

+0

當然可以。此代碼是在java –

+0

對不起,我明白不好 –

1

對於Directory.CreateDirectory(path)docuemtation狀態:

科瑞除非它們已經存在,否則指定指定路徑中的所有目錄和子目錄。從example source code修改

string path = @"c:\MyDir"; 

try 
{ 
    // Try to create the directory. 
    Directory.CreateDirectory(path); 
} 
catch (Exception e) 
{ 
    Console.WriteLine("The process failed: {0}", e.ToString()); 
} 
finally {} 

有上dotnetperls一個真正偉大的教程包含示例代碼,異常,提示和其他有用的信息有關創建目錄!

查找that SO-question創建相同的目錄文件夾內的可執行文件已經開始,或簡單的使用relative paths instead of absolute ones

Directory.CreateDirectory("Test"); 

這樣,你將永遠不會有關於尋找正確的路徑衝突!