StreamWriter无法在C#中工作

tvo*_*tko 6 c# streamwriter streamreader

这段代码在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.");
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

ran*_*ild 7

您需要关闭StreamWriter.像这样:

using(var sr = new StreamReader("..."))
using(var sw = new StreamWriter("..."))
{
   ...
}
Run Code Online (Sandbox Code Playgroud)

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

  • +1为最佳"最佳实践".所有IDisposable对象应该(几乎总是)与using语句配对. (2认同)

Rah*_*thi 5

Flush()写完后你需要StreamWriter.

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

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

sw.Close();  //or tw.Flush();
Run Code Online (Sandbox Code Playgroud)

您还可以查看StreamWriter.AutoFlush属性

获取或设置一个值,该值指示StreamWriter在每次调用StreamWriter.Write后是否将其缓冲区刷新到基础流.

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

提供方便的语法,确保正确使用IDisposable对象.

例:

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

  • 或者事件更好,关闭它 (4认同)
  • 您应该在StreamReader和StreamWriter上使用"using"语句. (2认同)