C#StreamWriter跨方法

时间:2014-04-27 08:24:37

标签: c# streamwriter xmlwriter

如何在类中的各种方法中使用相同的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"中实例化。方法将从那里调用。

任何帮助都将受到高度赞赏。

4 个答案:

答案 0 :(得分:0)

我只是在方法(全局变量)之上声明你的steamwriter并在方法内部进行工作

答案 1 :(得分:0)

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

答案 2 :(得分:-1)

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

答案 3 :(得分:-3)

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

}