跨方法的C#StreamWriter

本文关键字:C#StreamWriter 方法 | 更新日期: 2023-09-27 18:00:18

如何在类中的各种方法之间使用相同的StreamWriter。例如

public class XMLWriter
{       
  public export(string filename)       
  {
    StreamWriter sw = new StreamWriter(filename)
    sw.write("Line1")       
  }       
  public footer()       
  {
    // Note: I am not declaring streamwriter here since i want to use the same sw as in export method
    sw.write("Line x N")
  }                       
}

如何在多种方法中使用相同的sw。此外,这个类将从另一个类实例化,并从那里调用"public"方法。

如有任何帮助,我们将不胜感激。

跨方法的C#StreamWriter

sw声明为全局变量,并且只有在处理XMLWriter对象时(或者当您知道不会向文件中写入更多内容时)才关闭并处理它,并从创建该对象的类调用下面的DisposeWriter()方法:

public class MyClass
{
    private void DoSomeStuff()
    {
        XMLWriter xmlwr = new XMLWriter();
        xmlwr.export(@"C:'YourFile.txt");
        xmlwr.footer();
        xmlwr.DisposeWriter();
        wmlwr = null;
    }
}
public class XMLWriter
    {       
        private StreamWriter sw;
        public XMLWriter()
        {
            //this is the constructor, what you call with "new XMLWriter()"
        }
        public void export(string filename)       
        {
            sw = new StreamWriter(filename)
            sw.write("Line1")     
        }       
        public void footer()       
        {
            sw.write("Line x N")
        } 
        public void DisposeWriter()
        {
            sw.Close();
            sw.Dispose();
        }            
    }

我只需要在方法(全局变量)之上声明steamwriter,并在方法中完成工作

将其作为参数传递或使用私有字段-取决于您的要求。

using System;
using System.IO;
using System.Text;
public class XMLWriter
{
    //Objs
    private StreamWriter sw;
    private StringBuilder sb;
    //static items
    private string strHeader;
    private string strFooter;
    public XMLWriter()
    {
        //this is the constructor, what you call with "new XMLWriter()"
    }
    public void export(string filename)       
    {
        sb = new StringBuilder();
        sw = new StreamWriter(filename);
        sw.Write(strHeader + sb.ToString() + strFooter);
        sw.Close();
        sw.Dispose();
    }
    public string Footer
    {
        set
        {
            strFooter = value;
        }
    }
    public string Header
    {
        set
        {
            strHeader = value;
        }
    }
    public string LinesAdd
    {
        set
        {
            sb.Append(value);
        }
    }
}