hacikho
hacikho

Reputation: 147

How to safely copy file while another app writing in it, make sure both program not crash

I am managing a 3rd party vendor application which creates .txt files and write user logs into this .txt file, there are total of 10 log files, each has max size of 100 mb, when all reached max limit, vendor app wipes of the oldest one and start writing user logs into this one. To have a safe and permanent copy of all the files I create a C# console app which to copies these log files(txt) and paste into another safe location couple times in a day. However when my console app runs to copy the .txt log files sometimes it overlap with vendor app writing time, and vendor app crashes with an error:

"Unable to get the write to the current log file. Error: The process can not access the file 'C:\FileLocation\Log01.txt' because it is being used by another process. Please makes sure that the log files are not open in any other application".

I am wondering if there is anyway to copy whatever in the log file, and vendor app still has access to log file to write logs. Because when vendor app crashes, it stop writing logs into .txt file, and this can cause a huge issue.

Upvotes: 2

Views: 987

Answers (2)

user10216583
user10216583

Reputation:

Try reading and writing bytes instead of using the File.Copy(...) method. It works for me in similar situations such as backing up shared local databases over networks. Hopefully it works for you.

var srcPath = "SourcePath...";
var desFile = "DestinationPath...";            
var buffer = new byte[1024 * 1024];
var bytesRead = 0;

using (FileStream sr = new FileStream(srcPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (BufferedStream srb = new BufferedStream(sr))
using (FileStream sw = new FileStream(desFile, FileMode.Create, FileAccess.Write, FileShare.ReadWrite))
using (BufferedStream swb = new BufferedStream(sw))
{
    while(true)
    {
        bytesRead = srb.Read(buffer, 0, buffer.Length);
        if (bytesRead == 0) break;
        swb.Write(buffer, 0, bytesRead);
    }
    swb.Flush();
}

Good day.

Upvotes: 3

Rodrigo Machado
Rodrigo Machado

Reputation: 107

This is a concurrency problem. There is many ways to solve that, but all of them won't make the file just copy when another app is acessing that, this is impossible.

Try this website: https://www.oreilly.com/library/view/concurrency-in-c/9781491906675/ch01.html

You can also make all copies in the same system, it makes easer. But you will need to check if the file is open from another program.

Upvotes: 0

Related Questions