0

我创建了一个具有一些功能的类库并维护一个日志文件来跟踪执行的步骤。如果我在调试模式下运行这个类库,它会成功创建日志文件。

但是,我在创建该类库的 tlb 文件并安装到系统后创建了 cab 文件。现在我正在使用该库,所有功能都正常工作,只有日志文件没有写入。

我使用代码创建日志文件如下 -

 public static void LogTrace(string LogMessage)
    {
        try
        {

            string LogError = string.Empty;
            String DirPath = string.Empty;

            DirPath= Convert.ToString(ConfigurationSettings.AppSettings["DirPath"]);
            LogError = Convert.ToString(ConfigurationSettings.AppSettings["LogError"]);

            //if logging is not required
            if (LogError.ToLower() == "true")
            {
                if (DirPath == null || DirPath == string.Empty)
                    DirPath = @"C:\LogAndError";

                if (LogError == null || LogError == string.Empty)
                    LogError = "True";

                //creation of date wise file name

                string LogFileName = DirPath + "\\Log_ " + DateTime.Now.ToString("MM_dd_yyyy") + ".txt";
                createLogAndErrorFile(DirPath);

                    StreamWriter streamWriter = null;
                    streamWriter = new StreamWriter(LogFileName, true);
                    streamWriter.WriteLine("Time :" + DateTime.Now.ToString() + "  ");
                    streamWriter.WriteLine(LogMessage);
                    streamWriter.WriteLine(Environment.NewLine);
                    streamWriter.Flush();
                    streamWriter.Close();

            }
        }
        catch
        {
            //We are not throwing any exception because all the exeption is logged using this method
            //and throwing the exception could lead to recursive call of function.
        }
    }
    public static void createLogAndErrorFile(string DirPath)
    {
        if (!Directory.Exists(DirPath))
            Directory.CreateDirectory(DirPath);
    }
}

我错过了什么吗?

4

1 回答 1

0

验证您是否有权访问您的文件

将您的代码放在 try catch 块中并捕获异常我建议您使用 using 块

try
{

           var path = Path.Combine(DirPath, string.Concat("\\Log_",DateTime.Now.ToString("MM_dd_yyyy"), ".txt"));

            using (StreamWriter streamWriter = new StreamWriter(path))
            {
                streamWriter.WriteLine("Time :" + DateTime.Now.ToString() + "  ");
                streamWriter.WriteLine(LogMessage);
                streamWriter.WriteLine(Environment.NewLine);

            }


}
catch(Exception ex)
{
   Console.Write(ex.Message);
   throw ex;
}
于 2012-09-03T17:51:02.563 回答