Question

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
Was it helpful?

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

OTHER TIPS

Have you tried closing your FileStream? e.g.

var fs = File.Create(dstPath + "\\" + "File2.txt"); // causes lock
fs.Close();

i suggest you use a using statement:

using (var stream = File.Create(path))
{
   //....
}

but you should also be aware of using object initializers in using statements:

using (var stream = new FileStream(path) {Position = position})
{
  //....
}

in this case it will be compiled in:

var tmp = new FileStream(path);
tmp.Position = position;
var stream = tmp;

try
{ }
finally
{
    if (stream != null)
        ((IDisposable)stream).Dispose();
}

and if the Position setter throw exception, Dispose() will not being called for the temporary variable.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top