【问题标题】:Output in txt in C# Class library在 C# 类库中以 txt 格式输出
【发布时间】:2013-07-19 07:10:46
【问题描述】:

我怎样才能在txt中输出?但不在事件日志中

public class ProjectHandler:Microsoft.Office.Project.Server.Events.ProjectEventReceiver {

}

public static void WriteToEventLog(string textLog, EventLogEntryType logtype)  {
    EventLog eventlog = new EventLog();
    eventlog.Source = "Project Event Handler";
    eventlog.WriteEntry(logtype.ToString() + ":" + textLog, logtype);

}

public override void OnDeleting(PSContextInfo contextInfo, ProjectPreEventArgs e) {

    WriteToEventLog(string.Format("Пользователь \"{0}\" удалил проект \"{1}\"", contextInfo.UserName, e.ProjectName), EventLogEntryType.Information);

    base.OnDeleting(contextInfo, e);
}

【问题讨论】:

标签: c# output event-log


【解决方案1】:

您应该写入文本文件,而不是写入事件日志

添加此方法

 public static void WriteToTextFile(string textLog)
 {
    FileStream objFS = null;


    string strFilePath = AppDomain.CurrentDomain.BaseDirectory + @"\Exception Log\" + System.DateTime.Now.ToString("yyyy-MM-dd ") + "Exception.log";
    if (!File.Exists(strFilePath))
    {
          objFS = new FileStream(strFilePath, FileMode.Create);
    }
    else
          objFS = new FileStream(strFilePath, FileMode.Append);

    using (StreamWriter Sr = new StreamWriter(objFS))
     {
         Sr.WriteLine(System.DateTime.Now.ToShortTimeString() + "---" + textLog);
      }

 }

然后改变这一行

 WriteToEventLog(string.Format("Пользователь \"{0}\" удалил проект \"{1}\"", contextInfo.UserName, e.ProjectName), EventLogEntryType.Information);

 WriteToTextFile(string.Format("Пользователь \"{0}\" удалил проект \"{1}\"", contextInfo.UserName, e.ProjectName));

【讨论】:

    【解决方案2】:

    使用File.WriteAllText 方法。

    string path = @"c:\temp\MyTest.txt";
    string createText = "Hello and Welcome" + Environment.NewLine;
    File.WriteAllText(path, createText, Encoding.UTF8);
    

    【讨论】:

      【解决方案3】:
          public override void OnDeleting(PSContextInfo contextInfo, ProjectPreEventArgs e)
          {
              using (System.IO.StreamWriter sw = new System.IO.StreamWriter(@"C:\Blah.txt"))
              {
                  string textToWrite = string.Format("Пользователь \"{0}\" удалил проект \"{1}\"", contextInfo.UserName, e.ProjectName);
                  sw.WriteLine(textToWrite);
              }
          }
      

      类似的东西。使用 StreamWriter 对象。

      编辑 显然,请确保您有权写入 C:\ 驱动器等或您想写入的任何位置。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-17
        • 1970-01-01
        相关资源
        最近更新 更多