Đoạn mã này hoạt động hoàn hảo trong VS 2010. Bây giờ tôi có VS 2013 nó không còn ghi vào tệp. Nó không có lỗi hay gì cả. (Tôi nhận được một cảnh báo trong Notepad ++ nói rằng tập tin đã được cập nhật, nhưng không có gì được viết.)StreamWriter Không hoạt động trong C#
Tất cả đều ổn với tôi. Bất kỳ ý tưởng?
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.");
}
}
}
}
bạn đang tìm kiếm đúng thư mục? bạn đã mở tập tin như là một kiểm tra sanity? – user1666620
Hãy thử xóa rõ ràng. – Lloyd
Tôi không thấy bất cứ nơi nào mà bạn gọi sw.Close(); Nếu bạn làm như vậy, ghi sẽ được xóa và tệp đã đóng. Ngoài ra, bạn thực sự nên xem xét gói StreamReader và StreamWriter bằng cách sử dụng các khối - cả hai đều triển khai IDisposable và sẽ tự động đóng khi bạn rời khối sử dụng – thorkia