Streamwriter 覆盖 txt 文件中的文本

发布于 2024-12-08 00:31:39 字数 801 浏览 0 评论 0原文

有没有什么方法可以重新打开流写入器而不创建新的写入对象?因为此时,当调用 WriteOdd 时,streamwriter 正在覆盖在它之前调用的 WriteEven :/

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

谢谢

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

柠檬色的秋千 2024-12-15 00:31:39

使用重载,询问您是否要附加

public StreamWriter(
    string path,
    bool append
)

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

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

坐在坟头思考人生 2024-12-15 00:31:39

您可以将流对象传递给 WriteEven() 和 WriteOdd() 方法。

public void WriteOdd(StreamWiter writer)
{
  for (int i = 1; i < array.Length; i += 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)
  ...
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文