C#将文件从本地计算机复制到远程共享失败

时间:2018-07-03 06:43:38

标签: c# .net

我正在通过简单的方法将xml个文件从本地计算机复制到远程共享

DataTable dt = new DataTable();

// composing dt

string file = "test.xml";
string path = Path.Combine(@"C:\local\path", file);
string path2 = Path.Combine(@"\\path\to\remote\share", file);

if (File.Exists(path2)) File.Delete(path2);
dt.WriteXml(path);
File.Copy(path, path2);

我注意到有时复制意外结束于文件中间。 因此,我必须比较源文件和目标文件,以确保它已被完全复制。

如何在不进行比较的情况下强制成功复制?

2 个答案:

答案 0 :(得分:2)

文件复制的一般原因是超时,拒绝访问或网络中断。 尝试在复制操作1周围进行尝试捕获,以识别两次停止之间的原因。 如果您可以对另一个本地文件夹执行相同的操作,然后成功启动复制到网络,则唯一的原因可能是网络不稳定。 尝试使用一个很小的文件(一些KB)来查看操作是否成功。这将尝试解决由于文件大小而引起的超时问题。

对于非常大的文件,您必须设置发送者和接收者应用程序。您可以按照此MSDN帖子https://blogs.msdn.microsoft.com/webapps/2012/09/06/wcf-chunking/

中所述使用WCF块化或流式传输

答案 1 :(得分:1)

我建议比较源文件和目标文件的校验和,以了解复制是否成功。如果不成功,则可以根据要求采用不同的策略重试或快速失败。

class Program
{
    private string fileName = "myFile.xml";
    private string sourcePath = @"d:\source\" + fileName;        
    private string destinationPath = @"d:\destination\" + fileName;


    static void Main(string[] args)
    {           
        (new Program()).Run();
    }

    void Run()
    {
        PrepareSourceFile();
        CopyFile();
    }

    private void PrepareSourceFile()
    {
        DataTable helloWorldData = new DataTable("HelloWorld");            
        helloWorldData.Columns.Add(new DataColumn("Greetings"));
        DataRow dr = helloWorldData.NewRow();
        dr["Greetings"] = "Ola!";
        helloWorldData.Rows.Add(dr);
        helloWorldData.WriteXml(sourcePath);
    }

    private void CopyFile()
    {
        int numberOfRetries = 3; // I want to retry at least these many times before giving up.
        do
        {   
            try
            {
                File.Copy(sourcePath, destinationPath, true);
            }
            finally
            {
                if (CompareChecksum())
                    numberOfRetries = 0;
            }


        } while (numberOfRetries > 0);
    }


    private bool CompareChecksum()
    {
        bool doesChecksumMatch = false;
        if (GetChecksum(sourcePath) == GetChecksum(destinationPath))
            doesChecksumMatch = true;
        return doesChecksumMatch;
    }

    private string GetChecksum(string file)
    {
        using (FileStream stream = File.OpenRead(file))
        {
            SHA256Managed sha = new SHA256Managed();
            byte[] checksum = sha.ComputeHash(stream);
            return BitConverter.ToString(checksum).Replace("-", String.Empty);
        }
    }
}
相关问题