Streamwriter overwriting the text in txtfile

杀马特。学长 韩版系。学妹 提交于 2019-12-20 07:06:19

问题


Is there some way to reopen streamwriter without it creating a new object to write to? Because at the moment, when WriteOdd is called, streamwriter is overwriting WriteEven, which is called before it :/

public void WriteEven()
        {

           StreamWriter writer = new StreamWriter(FILENAME);   
           for (int i = 0; i < array.Length; i+= 2)
            {
                Console.WriteLine(array[i]);

                writer.WriteLine("EvenNumbers: " + array[i]);

            }

            writer.Close();


        }

        public void WriteOdd()
        {
            StreamWriter writer = new StreamWriter(FILENAME);
            for (int i = 1; i < array.Length; i += 2)
            {
                Console.WriteLine(array[i]);


                writer.WriteLine("OddNumbers: " + array[i]);


            }
            writer.Close();
        }   

Thanks


回答1:


Use the overload that asks you if you want to append

public StreamWriter(
    string path,
    bool append
)

http://msdn.microsoft.com/en-us/library/36b035cb.aspx




回答2:


You can pass stream object to WriteEven() and WriteOdd() methods.

public void WriteOdd(StreamWiter writer)
{
  for (int i = 1; i < array.Length; i += 2)
  ...
}


来源:https://stackoverflow.com/questions/7656580/streamwriter-overwriting-the-text-in-txtfile

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!