StreamWriter无法在C#中工作

时间:2015-06-17 13:19:09

标签: c# streamreader streamwriter

这段代码在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.");
            }
        }
    }
}

2 个答案:

答案 0 :(得分:7)

您需要关闭StreamWriter。像这样:

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

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

答案 1 :(得分:5)

写完后你需要Flush() StreamWriter。

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

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

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

您还可以查看StreamWriter.AutoFlush Property

  

获取或设置一个值,指示StreamWriter是否将刷新   每次调用后它的缓冲区到底层流   StreamWriter.Write。

另一个现在非常受欢迎并且推荐使用的选项是使用照顾它的using statement

  

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

示例:

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