gpt4 book ai didi

c# - 在StreamWriter中使用file.Close()

转载 作者:太空宇宙 更新时间:2023-11-03 18:15:59 24 4
gpt4 key购买 nike

我在尝试使用该文件时遇到问题。在此方法中使用StreamWriter关闭,它似乎不喜欢它。有人可以演示如何做到这一点。 (之所以这样,是因为另一个方法访问了正在使用的文件,因此无法访问,因为该文件仍在被另一个方法使用。)

到目前为止的代码:

private static void TrimColon()
{
using (StreamWriter sw = File.AppendText(@"process_trimmed.lst"))
{
StreamReader sr = new StreamReader(@"process_trim.lst");
string myString = "";
while (!sr.EndOfStream)
{

myString = sr.ReadLine();
int index = myString.LastIndexOf(":");
if (index > 0)
myString = myString.Substring(0, index);

sw.WriteLine(myString);
}
}
}

最佳答案

private static void TrimColon(String inputFilePath, String outputFilePath)
{
//Error checking file paths
if (String.IsNullOrWhiteSpace(inputFilePath))
throw new ArgumentException("inputFilePath");
if (String.IsNullOrWhiteSpace(outputFilePath))
throw new ArgumentException("outputFilePath");

//Check to see if files exist? - Up to you, I would.

using (var streamReader = File.OpenText(inputFilePath))
using (var streamWriter = File.AppendText(outputFilePath))
{
var text = String.Empty;

while (!streamReader.EndOfStream)
{
text = streamReader.ReadLine();

var index = text.LastIndexOf(":");
if (index > 0)
text = text.Substring(0, index);

streamWriter.WriteLine(text);
}
}
}

关于c# - 在StreamWriter中使用file.Close(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6396176/

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