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

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

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();
}

“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?

        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();
        }

“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

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);
    }
}

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:

确定