我创建了一个具有某些功能的类库,并维护一个日志文件来跟踪执行的步骤。如果我在调试模式下运行此类库,它就会成功创建日志文件。
但是,我在创建该类库的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);
}
}
我错过了什么吗?
答案 0 :(得分:0)
确认您有权访问您的文件
将代码放在try catch块中并捕获异常 我建议你使用块
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;
}