S Nash
S Nash

Reputation: 2499

Does copying a file cause it to lock

On web server, I have an ASP.NET website with error.txt inside it.

This file always gets written to. And it is in the bin folder.

Should I be concerned if:

  1. I go to web server and open the bin folder
  2. Go to web server and open the error.txt

My C# code always writes to it in a share mode FileShare.ReadWrite

Is copying the file to another folder using command prompt safer to avoid locking?

Upvotes: 0

Views: 3486

Answers (1)

Tony Hinkle
Tony Hinkle

Reputation: 4742

It depends on the application you are opening it with. For instance, if you open it with Microsoft Word, it will lock the file and other processes will only be able to read it. However, if you open it with Notepad, the file is not locked and another process can read, write, delete, move, or rename it.

You can test simply by opening a file with the application, and then try to delete, rename, write to, or move the file. If you can perform any of those actions then you know that your application did not lock it.

Assuming you are just copying it with Explorer, copying the file will lock it for the time it takes to read the file. If it is a small file, this will just be a very few milliseconds.

To ensure that your application doesn't crash if it tries to write to the file while it is locked, put the write operation(s) in a loop that retry if an exception is returned, with a 100 ms wait between tries.

Upvotes: 2

Related Questions