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

后端 未结 2 694
甜味超标
甜味超标 2021-01-16 06:29

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,

相关标签:
2条回答
  • 2021-01-16 07:00

    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.

    0 讨论(0)
  • 2021-01-16 07:03

    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.

    0 讨论(0)
提交回复
热议问题