簡體   English   中英

在C#中的Windows Service中為日志事件文件創建新目錄

[英]Creating a new directory for log event file in windows service in c#

我想知道如何通過c#在Windows服務中為日志事件文件創建新目錄

我有以下代碼:

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

作為Directory.CreateDirectory(path)文檔狀態:

除非已存在,否則在指定路徑中創建所有目錄和子目錄。

示例源代碼修改:

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上有一個非常不錯的教程, 其中包含示例代碼,異常,提示以及有關創建目錄的其他有用信息!

查找該SO問題以在可執行文件已啟動的同一目錄中創建文件夾,或者簡單地使用相對路徑而不是絕對路徑

Directory.CreateDirectory("Test");

這樣一來,您就不會在尋找正確的路徑上發生沖突!

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM