“The process cannot access the file because it is being used by another process” error.

huangapple go评论98阅读模式
英文:

C# "The process cannot access the file because it is being used by another process" error

问题

我一直在尝试找出我的错误是什么,已经有几分钟了。有人能帮忙吗?

  1. public void UpdateItemList(string word, string replacement)
  2. {
  3. StreamReader reader = new StreamReader("items.txt");
  4. string input = reader.ReadToEnd();
  5. using (StreamWriter writer = new StreamWriter("items.txt", true))
  6. {
  7. string output = input.Replace(word, replacement);
  8. writer.Write(output);
  9. }
  10. writer.Close();
  11. reader.Close();
  12. }

“The process cannot access the file because it is being used by another process” error.

我添加了 reader.Close()writer.Close(),并进行了不同的排列,我不确定我漏掉了什么。

英文:

I've been trying to figure out what's my error here for a few minutes now. can someone help?

  1. public void UpdateItemList(string word, string replacement)
  2. {
  3. StreamReader reader = new StreamReader("items.txt");
  4. string input = reader.ReadToEnd();
  5. using (StreamWriter writer = new StreamWriter("items.txt", true))
  6. {
  7. {
  8. string output = input.Replace(word, replacement);
  9. writer.Write(output);
  10. }
  11. writer.Close();
  12. }
  13. reader.Close();
  14. }

“The process cannot access the file because it is being used by another process” error.

I added reader.Close() and writer.Close() and gave different orientation, I'm not sure what I'm missing.

答案1

得分: 2

你应该在打开StreamWriter之前关闭StreamReader

  1. public void UpdateItemList(string word, string replacement)
  2. {
  3. string input;
  4. using (StreamReader reader = new StreamReader("items.txt"))
  5. {
  6. input = reader.ReadToEnd();
  7. }
  8. using (StreamWriter writer = new StreamWriter("items.txt", false))
  9. {
  10. string output = input.Replace(word, replacement);
  11. writer.Write(output);
  12. }
  13. }
英文:

you should close StreamReader before opening streamWriter

  1. public void UpdateItemList(string word, string replacement)
  2. {
  3. string input;
  4. using (StreamReader reader = new StreamReader("items.txt"))
  5. {
  6. input = reader.ReadToEnd();
  7. }
  8. using (StreamWriter writer = new StreamWriter("items.txt", false))
  9. {
  10. string output = input.Replace(word, replacement);
  11. writer.Write(output);
  12. }
  13. }

huangapple
  • 本文由 发表于 2023年2月18日 23:49:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/75494498.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定