Search code examples
c#networkingdata-integrity

Handle network fail while copying files in C#


I am writing a C# app that copy files over a network, the problem is that the size of the files and folders to copy is more than 1 TB. My method is as follows

public static void SubmitDocsToRepository(string p_FilePaths) 
{
   IEnumerable<(string,string)> directoryLevels = GetAllFolders(p_FilePaths);
   IEnumerable<(string,string)> filesLevels = GetAllFiles(p_FilePaths);

   foreach (var tuple in directoryLevels) 
       Folder copy logic
   foreach (var tuple in filesLevels) 
       File copy logic                     
}

Which would work fine, but assuming something would happen to the network or remote server or the electric power gets lost for whatever reason what should I add to this code to allow me to continue where I left off, especially how could I retrace my steps to where I was.


Solution

  • It could be something like this:

    public static void SubmitDocsToRepository(string p_FilePaths)
    {
        IEnumerable<(string, string)> directoryLevels = GetAllFolders(p_FilePaths);
        IEnumerable<(string, string)> filesLevels = GetAllFiles(p_FilePaths);
    
        foreach (var tuple in directoryLevels)
            while (!CopyDirectory(tuple)) ;
    
        foreach (var tuple in filesLevels)
            while (!CopyFile(tuple)) ;
    }
    
    static bool CopyDirectory((string, string)tuple)
    {
        try
        {
            // Copy logic
        } 
        catch 
        { 
            // Some logging here
            return false;
        }
    
        return true;
    }
    
    static bool CopyFile((string, string) tuple)
    {
        try
        {
            // Copy logic
        }
        catch
        {
            // Some logging here
            return false;
        }
    
        return true;
    }