[英]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.");
}
}
}
}
您需要关闭StreamWriter。 像这样:
using(var sr = new StreamReader("..."))
using(var sw = new StreamWriter("..."))
{
...
}
即使抛出异常,这也会关闭流。
你需要在写入后Flush()
StreamWriter。
默认情况下,StreamWriter是缓冲的,这意味着它在收到Flush()或Close()调用之前不会输出。
你也可以尝试这样关闭它:
sw.Close(); //or tw.Flush();
您还可以查看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"))
{
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.