英文:
C# "The process cannot access the file because it is being used by another process" error
问题
我一直在尝试找出我的错误是什么,已经有几分钟了。有人能帮忙吗?
public void UpdateItemList(string word, string replacement)
{
StreamReader reader = new StreamReader("items.txt");
string input = reader.ReadToEnd();
using (StreamWriter writer = new StreamWriter("items.txt", true))
{
string output = input.Replace(word, replacement);
writer.Write(output);
}
writer.Close();
reader.Close();
}
我添加了 reader.Close()
和 writer.Close()
,并进行了不同的排列,我不确定我漏掉了什么。
英文:
I've been trying to figure out what's my error here for a few minutes now. can someone help?
public void UpdateItemList(string word, string replacement)
{
StreamReader reader = new StreamReader("items.txt");
string input = reader.ReadToEnd();
using (StreamWriter writer = new StreamWriter("items.txt", true))
{
{
string output = input.Replace(word, replacement);
writer.Write(output);
}
writer.Close();
}
reader.Close();
}
I added reader.Close() and writer.Close() and gave different orientation, I'm not sure what I'm missing.
答案1
得分: 2
你应该在打开StreamWriter
之前关闭StreamReader
。
public void UpdateItemList(string word, string replacement)
{
string input;
using (StreamReader reader = new StreamReader("items.txt"))
{
input = reader.ReadToEnd();
}
using (StreamWriter writer = new StreamWriter("items.txt", false))
{
string output = input.Replace(word, replacement);
writer.Write(output);
}
}
英文:
you should close StreamReader
before opening streamWriter
public void UpdateItemList(string word, string replacement)
{
string input;
using (StreamReader reader = new StreamReader("items.txt"))
{
input = reader.ReadToEnd();
}
using (StreamWriter writer = new StreamWriter("items.txt", false))
{
string output = input.Replace(word, replacement);
writer.Write(output);
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论