-2

While writing a file in a single thread application, I get the error

"The process cannot access the file because it is being used by another process".

I open all writer objects in the using keyword. Although it is a single thread, I lock functions every time with ReaderWriterLockSlim and unlock them when I'm done. However, I am getting an error. Anything on your mind?

There are only these two functions that communicate with the file. One is appending, the other is cleaning the file.

 public void WriteToFileThreadSafe(string text, string fileName)
        {
            string path = ApplicationDirectory + "/" + fileName;
            _readWriteLock.EnterWriteLock();
            try
            {
                if (File.Exists(path))
                {
                    using (StreamWriter sw = File.AppendText(path))
                    {
                        sw.WriteLine(text);
                        sw.Close();
                    }
                }
            }
            finally
            {
                _readWriteLock.ExitWriteLock();
            }
        }

        public void ClearTextFile(string fileName)
        {
            string path = ApplicationDirectory + "/" + fileName;
            _readWriteLock.EnterWriteLock();
            try
            {
                using (FileStream sw = File.Create(path))
                {
                    sw.Close();
                }
            }
            finally
            {
                _readWriteLock.ExitWriteLock();
            }
        }
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
  • Can you add your lock implementation? – Gilvan Júnior Aug 11 '21 at 20:16
  • What process is locking your file? Can you ensure it is your program? https://superuser.com/q/117902 – Eric J. Aug 11 '21 at 20:26
  • @GilvanJúnior see [ReaderWriterLockSlim](https://learn.microsoft.com/en-us/dotnet/api/system.threading.readerwriterlockslim?view=net-5.0) – Steeeve Aug 11 '21 at 20:32
  • There is nothing obviously wrong with your presented code. You don't need `sw.Close` in the using blocks but it's not an error. And you should use Path.Combine instead of string concatenation. You could make a try with [Process Monitor](https://learn.microsoft.com/en-us/sysinternals/downloads/procmon) to see which processes are accessing the file, maybe antivirus or windows search indexer. – Steeeve Aug 11 '21 at 20:54

1 Answers1

0

thank you for your answers. I found problem. Program sends mail periodically. I didn't use using for mail and attachment instances. So, Garbage collector doesn't delete mail objects and program flow continue.. When any this function called program shutdown :D Thank you for your answers again. –