TextWriterTraceListener 和设计时属性支持文件xmta

本文介绍如何使用TextWriterTraceListener类记录日志到文件。通过示例代码展示如何创建TextWriterTraceListener实例并将其添加到Trace监听器中,同时提供通过配置文件设置日志输出的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

TextWriterTraceListener 可行进行简单的日志记录

下面的示例实现 TextWriterTraceListener 类的一个实例,该类使用名为 myOutputWriter 的 StreamWriter 写入一个名为 TestFile.txt 的文件。 首先,此示例创建用于输出的文件。 然后,它为第一个文本编写器创建 StreamWriter,将输出文件分配给它,并将其添加到 Listeners。 然后,该代码将一行文本输出到该文件。 最后,该示例刷新输出缓冲区。

在运行此示例后,可以打开 TestFile.txt 文件查看输出。

public class Sample
{

public static int Main(string[] args) {
    // Create a file for output named TestFile.txt.
    Stream myFile = File.Create("TestFile.txt");

    /* Create a new text writer using the output stream, and add it to
     * the trace listeners. */
    TextWriterTraceListener myTextListener = new
       TextWriterTraceListener(myFile);
    Trace.Listeners.Add(myTextListener);

    // Write output to the file.
    Trace.Write("Test output ");


    // Flush the output.
    Trace.Flush();

    return 0;
 }

}

 

另外我们可以通过配置App.config来生成日志文件

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.diagnostics>
    <trace autoflush="false" indentsize="4">
      <listeners>
        <add name="myListener" type="System.Diagnostics.TextWriterTraceListener" initializeData="aa.log"></add>
        <remove name="Default"></remove>
      </listeners>
    </trace>
  </system.diagnostics>
</configuration>

然后直接在代码中用Trace.write("aaaaa");Trace.flush();就能写入相关文件

因为是直接配置在App.config中,所以部署的时候一定要记得带上.exe.config文件,应用程序是运行的时候会读取这个配置文件.

或者你把App.config属性设置其为嵌入的资源,那样子就会嵌入到exe文件中去了. 

 

DesignTimeAttributes1.xmta文件(有时候我们在设置控件时调用了dllimport引入外部dll文件后,我们的自定控件就不能正常显示,加上这个文件,就能解决问题):

<?xml version="1.0" encoding="utf-16"?>
<Classes xmlns="http://schemas.microsoft.com/VisualStudio/2004/03/SmartDevices/XMTA.xsd">
  <Class Name="DeliveryInHand.ModelForm">
    <DesktopCompatible>true</DesktopCompatible>
  </Class>
</Classes>

 

转载于:https://www.cnblogs.com/fujinliang/archive/2012/07/19/2599621.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值