Search code examples
c#directorylocked-files

Directory is locked after creation of file while program is running


After I created a file in a directory the directory is locked as long as my program which created the file is running. Is there any way to release the lock? I need to rename the directory couple of lines later and I always get an IOException saying "Access to the path "..." denied".

Directory.CreateDirectory(dstPath);
File.Copy(srcPath + "\\File1.txt", dstPath + "\\File1.txt"); // no lock yet
File.Create(dstPath + "\\" + "File2.txt"); // causes lock

Solution

  • File.Create(string path) Creates a file and leaves the stream open.

    you need to do the following:

    Directory.CreateDirectory(dstPath);
    File.Copy(srcPath + "\\File1.txt", dstPath + "\\File1.txt");
    using (var stream = File.Create(dstPath + "\\" + "File2.txt"))
    {
        //you can write to the file here
    }
    

    The using statement asures you that the stream will be closed and the lock to the file will be released.

    Hope this helps