這段代碼在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.");
}
}
}
}
你在尋找正確的目錄嗎?你是否打開該文件作爲完整性檢查? – user1666620
嘗試顯式刷新以及。 – Lloyd
我沒有看到任何你稱之爲sw.Close();如果你這樣做,寫入將被刷新並關閉文件。此外,你應該看看包裹的StreamReader和StreamWriter使用塊 - 它們都實現IDisposable,而當你離開使用塊 – thorkia