2015-06-17 116 views
6

这段代码在VS 2010中工作得很完美。现在我有了VS 2013,它不再写入文件。它没有错误或任何东西。 (我在记事本中得到一个警报++,说明该文件已被更新,但并没有什么写的。)StreamWriter不能在C#中工作

这一切看起来好像没什么问题。有任何想法吗?

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."); 
      } 
     } 
    } 
} 
+0

你在寻找正确的目录吗?你是否打开该文件作为完整性检查? – user1666620

+0

尝试显式刷新以及。 – Lloyd

+4

我没有看到任何你称之为sw.Close();如果你这样做,写入将被刷新并关闭文件。此外,你应该看看包裹的StreamReader和StreamWriter使用块 - 它们都实现IDisposable,而当你离开使用块 – thorkia

回答

5

您需要在写入后写入StreamWriter Flush()

默认的StreamWriter被缓冲,这意味着它不会输出,直到它接收一个冲洗()或关闭()调用。

此外,您还可以尝试关闭它是这样的:

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

你也可以看看StreamWriter.AutoFlush Property

获取或设置指示的StreamWriter是否会刷新 其缓冲值在每次调用 StreamWriter.Write之后将其发送到基础流。

另一种选择,现在是一个非常流行和推荐的日子是使用using statement照顾它。

提供了一种方便的语法,可以确保正确使用ID为一次性的对象 。

例子:

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

或事件更好,关闭它 –

+2

您应该在StreamReader和StreamWriter上使用“using”语句。 – tdbeckett

+0

@tdbeckett: - 是的,这是标准和推荐的方式!感谢您指出! –

7

您需要关闭的StreamWriter。像这样:

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

即使发生异常,这也会关闭流。

+2

+1最佳“最佳实践”。所有的IDisposable对象应该(几乎总是)与using语句配对。 –

+0

是的,应该使用使用语句 - 不需要明确地调用Flush/Close,这样更整洁。 ((line = sr.ReadLine())!= null) //将该行写入控制台窗口 Console.WriteLine(line); – Polyfun

+0

该行可以通过将readline和比较 组合起来进行清理。 int myVal = 3; 对(INT I = 0; I'设为myVal;我++){ 控制台。的WriteLine(线); sw.WriteLine(line); } //写入其他文件 sw.WriteLine(line); } – thorkia