3

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
Cœur
  • 37,241
  • 25
  • 195
  • 267
theknut
  • 2,533
  • 5
  • 26
  • 41

3 Answers3

8

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

Arturo Martinez
  • 3,737
  • 1
  • 22
  • 35
4

Have you tried closing your FileStream? e.g.

var fs = File.Create(dstPath + "\\" + "File2.txt"); // causes lock
fs.Close();
George Johnston
  • 31,652
  • 27
  • 127
  • 172
  • 5
    Note that it's good practice to wrap file open/create in `using`, in case of exceptions. Not significant for this one-liner, but if there was other code between the Create() and the Close() that could throw exceptions, it's necessary. – Matthew Watson Apr 19 '13 at 13:42
  • @MatthewWatson Agreed. Arturo's solution is appropriate. – George Johnston Apr 19 '13 at 13:45
2

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.

Dzmitry Martavoi
  • 6,867
  • 6
  • 38
  • 59
  • Which is not the case here; `File.Open(path)` and `File.Create(path)` cannot be expressed with object initialization because they are not constructors, they are static methods. The syntax in your second using statement won't even compile. – Arturo Martinez Apr 19 '13 at 18:36
  • @ArturoMartinez: yes, there should be an object constructor for reproducing such scenario. i fixed it (FileStream insted of File.Open()). – Dzmitry Martavoi Apr 19 '13 at 18:39