在C#类库中以txt格式输出

本文关键字:txt 格式 输出 类库 | 更新日期: 2023-09-27 18:23:57

如何在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#类库中以txt格式输出

与其写入事件日志,不如写入文本文件

添加此方法

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

使用File.WriteAllText方法。

string path = @"c:'temp'MyTest.txt";
string createText = "Hello and Welcome" + Environment.NewLine;
File.WriteAllText(path, createText, Encoding.UTF8);
    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:''驱动器等或任何您想写入的位置。