StreamWriter 在 C# 中不工作

StreamWriter Not working in C#

这段代码在 VS 2010 中完美运行。现在我有了 VS 2013,它不再写入文件。它没有错误或任何东西。 (我在 Notepad++ 中收到一条警告,指出文件已更新,但没有写入任何内容。)

我觉得一切都很好。有什么想法吗?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            String line;
            try
            {
                //Pass the file path and file name to the StreamReader constructor
                StreamReader sr = new StreamReader("C:\Temp1\test1.txt");
                StreamWriter sw = new StreamWriter("C:\Temp2\test2.txt");

                //Read the first line of text
                line = sr.ReadLine();

                //Continue to read until you reach end of file
                while (line != null)
                {
                    //write the line to console window
                    Console.WriteLine(line);
                    int myVal = 3;
                    for (int i = 0; i < myVal; i++)
                    {
                        Console.WriteLine(line);
                        sw.WriteLine(line);
                    }
                    //Write to the other file
                    sw.WriteLine(line);
                    //Read the next line
                    line = sr.ReadLine();
                }

                //close the file
                sr.Close();
                Console.ReadLine();
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception: " + e.Message);
            }
            finally
            {
                Console.WriteLine("Executing finally block.");
            }
        }
    }
}

写入后需要Flush() StreamWriter。

默认情况下,StreamWriter 是缓冲的,这意味着它在收到 Flush() 或 Close() 调用之前不会输出。

另外你也可以尝试这样关闭它:

sw.Close();  //or tw.Flush();

你也可以看看StreamWriter.AutoFlush Property

Gets or sets a value indicating whether the StreamWriter will flush its buffer to the underlying stream after every call to StreamWriter.Write.

另一个现在非常流行和推荐的选项是使用 using statement 来处理它。

Provides a convenient syntax that ensures the correct use of IDisposable objects.

示例:

using(var sr = new StreamReader("C:\Temp1\test1.txt"))
using(var sw = new StreamWriter("C:\Temp2\test2.txt"))
{
   ...
}

您需要关闭 StreamWriter。像这样:

using(var sr = new StreamReader("..."))
using(var sw = new StreamWriter("..."))
{
   ...
}

即使抛出异常,这也会关闭流。