theknut
theknut

Reputation: 2553

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

Upvotes: 3

Views: 1504

Answers (3)

martavoi
martavoi

Reputation: 7082

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.

Upvotes: 2

Arturo Martinez
Arturo Martinez

Reputation: 2583

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

Upvotes: 8

George Johnston
George Johnston

Reputation: 32258

Have you tried closing your FileStream? e.g.

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

Upvotes: 4

Related Questions