[英]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.