【发布时间】:2015-09-02 18:18:48
【问题描述】:
这段代码在 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.");
}
}
}
}
【问题讨论】:
-
您在寻找正确的目录吗?您是否已将文件作为完整性检查打开?
-
也尝试显式刷新。
-
我没有看到你调用 sw.Close();如果你这样做,写入将被刷新并关闭文件。此外,您应该真正考虑将 StreamReader 和 StreamWriter 包装在 using 块中 - 它们都实现 IDisposable,并且在您离开 using 块时会自动关闭
-
此外,明确关闭您的流是个好主意。你正在关闭你的流阅读器,但不是作者。
标签: c# streamreader streamwriter