gpt4 book ai didi

c# - StreamWriter 在 C# 中不工作

转载 作者:太空狗 更新时间:2023-10-29 21:04:35 24 4
gpt4 key购买 nike

这段代码在 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("..."))
{
...
}

即使抛出异常,这也会关闭流。

关于c# - StreamWriter 在 C# 中不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30892847/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com