I am using the following code in C# Windows Service to create or overwrite an existing file.
function DonwnloadFile(string destinationfolder, string filename)
{
using (var outputFileStream = System.IO.File.Create(
destinationfolder + "\\" + filename, BUFFER_SIZE))
{
//Downloads a large file from cloud and writes it to the outputFileStream
//...
//...
}
}
While the file (which is very large in size) is getting downloaded, another request to DownloadFile
method is made since the source file got updated.
However, an exception is thrown:
The process cannot access the file '[FileName with Path]' because it is being used by another process.
How do I implement a solution so that subsequent requests to overwrite the same file wait till the previous file write operation for the same file finishes. Also, the solution should allow requests to a overwrite a different file should not wait as it won't throw any exception.
Can I use lock while ensuring lock only works based on the filename. Or can someone please suggest a better solution for the problem.
Note: DonwloadFile
method would be called by a different thread each time.