System.IO.IOException: 'The process cannot access the file '@.txt' because it is being used by another process.'

后端 未结 6 600
野的像风
野的像风 2021-01-11 13:15

I am new to programming and I have a question. If I have two functions, one creates a text file and writes into it, while the other opens the same text file and reads from i

6条回答
  •  鱼传尺愫
    2021-01-11 13:39

    The issue is sometimes file locks don't get released immediately after they are closed.

    You can try run a loop to read the file. Inside the loop put a try catch statement and if the file reads successfully break from the loop. Otherwise, wait a few milliseconds and try to read the file again:

    string originalText = null;
    while (true)
    {
        try
        {
            originalText = File.ReadAllText(@"C:\Users\...\fileName.txt", Encoding.Default);
            break;
        }
        catch 
        { 
            System.Threading.Thread.Sleep(100);
        }
    }
    

提交回复
热议问题