-1

Take the following code snipit:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace filetest
{
    class Program
    {
        static void Main(string[] args)
        {
            string testString = "Test File";
            string testFileName = Guid.NewGuid().ToString() + ".txt";
            string storagePath = "Z:";

            File.WriteAllText(storagePath + "\\" + testFileName, testString);
            string input = File.ReadAllText(storagePath + "\\" + testFileName);
            File.Delete(storagePath + "\\" + testFileName);
            Console.WriteLine("Complete");
            Console.ReadKey();
        }
    }
}

Where Z: is a mapped drive to another machine or NAS. When running this code, there is an exception on the File.ReadAllText line:

System.IO.IOException: The process cannot access the file 'Z:\4c639f96-12a9-410d-94a0-ffc6392aa85a.txt' because it is being used by another process.
   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
   at System.IO.StreamReader..ctor(String path, Encoding encoding, Boolean detectEncodingFromByteOrderMarks, Int32 bufferSize, Boolean checkHost)
   at System.IO.File.InternalReadAllText(String path, Encoding encoding, Boolean checkHost)
   at System.IO.File.ReadAllText(String path)
   at Switchvox_VM_Handler.Controllers.FaxController.TestWriteStorageLocation(FaxStorage storage) in D:\tfs2017\Switchvox-VM-Handler\Switchvox-VM-Handler\Controllers\FaxController.cs:line 327

Additionally. that file while it can be opened in Notepad, cannot be deleted until the machine running this code is REBOOTED. Ending the process is not enough to release the lock. The lock stays in place forever.

I have witnessed this with .NET Framework 4.7, 4.72, 4.81. The same code does not cause this exception when reworked to .NET 6.

To me this seems like a bug with legacy .NET framework, but maybe I'm missing something. I've simplified it down to the bare minimum for this SO question and verified it still throws the same exception even as a 10 line console project. I have spent time breaking out the writing to the traditional way of using using streamwriter statements, etc, but same results. Also if I replace the File.WriteAllText with a File.Copy command and copy an existing text file to the same location, that file is left locked in the same manner.

Finally if that drive letter Z: is swapped with a local drive letter, i.e. C: it works perfectly fine as one would expect. It only seems to be an issue with network shares (SMB/CIFS).

Any thoughts on how to get around this as I'm not really ready to re-write this project in .NET 6 (core) yet.

achaffman
  • 1
  • 2
  • 2
    I hope you realize there is a very.... _very_ small chance that this is actually a framework bug. It is a lot more likely you have a mistake in your process/environment that is keeping the lock open from somewhere else. Try the [File Locksmith Powertool](https://learn.microsoft.com/en-us/windows/powertoys/file-locksmith) to see if you can identify which other processes might be holding on to that file. – julealgon Feb 16 '23 at 18:13
  • If I remember I thought you had to close out the file create, open, etc when working with it before doing another action. This may help: https://stackoverflow.com/questions/15120254/when-is-file-close-necessary – Brad Feb 16 '23 at 18:14
  • 2
    Totally agree with @julealgon; there's a much higher chance the issue is on the other side (maybe a virusscanner or something? maybe even a virusscanner on your end). @Brad: WriteAllText should [create, write, close](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.writealltext?view=netframework-4.7.2). Same goes for File.Copy. – RobIII Feb 16 '23 at 18:15
  • @RobIII, this was attempted on multiple source and destination PC's, even a NAS. I don't believe AV has anything to do with it, especially since the same code runs fine with no lock with .net 6/7. I was hoping someone else could build this code and reproduce as easily as I was able to. – achaffman Feb 16 '23 at 18:52
  • @achaffman As you can [clearly see](https://referencesource.microsoft.com/#mscorlib/system/io/file.cs,890) the `WriteAllText` method (which calls `InternalWriteAllText`) uses a `using` statement which guarantees disposal (and thus closure) of the file. It would have caused countless bugreports if any of this didn't work as documented. That's not to say the .Net framework can't, or doesn't, have any bugs. Just that it's very, very much more likely your code has a bug or you're using it incorrectly or some external factors (like AV's or whatever) are at play specific to _your_ situation. – RobIII Feb 16 '23 at 20:05
  • I have created a console project with your code targets .Net Framework 4.5 and could not reproduce the problem. – Paul Chen Feb 17 '23 at 02:14
  • Now I'm utterly confused - Webroot is the culprit, but only with .net framework. .net core does not experience the issue. Not sure the solution there, but at least I have something to go on. – achaffman Feb 17 '23 at 03:52
  • Use a tool like procmon to see what process has the lock – Daniel A. White Mar 23 '23 at 23:04

1 Answers1

0

I have been having the same issue with a WinFrom application that I have been working on updating... I have found that disconnecting and reconnecting the mapped network drive release the file without the need for a reboot however this file is still being locked. Originally the app was programmed for .Net 4.7 however I have since set the target framework to .Net6 and .Net7 and am still having the locked file issue "File in use by another process" The Application works without locking the file on other development pc's Will look further into the Webroot possibility

Mark Foad
  • 1
  • 1