@@ -61,16 +61,43 @@ public static void SyncFile(SftpClient sftp, string sourcePath, string destinati
6161 {
6262 Logger . LogInfo ( $ "Syncing { sourcePath } -> { destinationPath } ") ;
6363
64- //Because the VMS SFTP server uses Posix not RMS, and some older servers do not correctly
65- //handle truncating files when the content gets shorter (resulting in corruption at the end of the file),
66- //we delete the file first if it exists, before writing new content.
67- if ( sftp . Exists ( destinationPath ) )
64+ int retryCount = 0 ;
65+ const int maxRetries = 5 ;
66+ const int delayBetweenRetriesMs = 500 ;
67+
68+ while ( retryCount < maxRetries )
6869 {
69- sftp . DeleteFile ( destinationPath ) ;
70- }
70+ try
71+ {
72+ // Because the VMS SFTP server uses Posix not RMS, and some older servers do not correctly
73+ // handle truncating files when the content gets shorter (resulting in corruption at the end of the file),
74+ // we delete the file first if it exists, before writing new content.
75+ if ( sftp . Exists ( destinationPath ) )
76+ {
77+ sftp . DeleteFile ( destinationPath ) ;
78+ }
79+
80+ // Read the local file content
81+ var localFileContent = File . ReadAllText ( sourcePath ) ;
7182
72- //Write the file content to the destination path
73- sftp . WriteAllText ( destinationPath , File . ReadAllText ( sourcePath ) ) ;
83+ // Write the remote file
84+ sftp . WriteAllText ( destinationPath , localFileContent ) ;
85+
86+ return ;
87+ }
88+ catch ( Exception ex ) when ( ex is IOException || ex is FileNotFoundException )
89+ {
90+ retryCount ++ ;
91+ if ( retryCount >= maxRetries )
92+ {
93+ Logger . LogError ( $ "Failed to sync after { maxRetries } retries. Exception: { ex . Message } ") ;
94+ return ;
95+ }
96+
97+ Logger . LogInfo ( $ "Retry { retryCount } /{ maxRetries } after exception: { ex . Message } ") ;
98+ Thread . Sleep ( delayBetweenRetriesMs ) ;
99+ }
100+ }
74101 }
75102
76103 public static Task < IEnumerable < FileInfo > > SyncDirectoryAsync ( SftpClient sftp , string sourcePath , string destinationPath , string searchPattern )
@@ -265,7 +292,7 @@ private async void Fsw_Changed(object? sender, FileSystemEventArgs arg)
265292 }
266293
267294 while ( ! IsFileReady ( arg . FullPath ) )
268- await Task . Delay ( 50 ) ;
295+ await Task . Delay ( 25 ) ;
269296
270297
271298 lock ( _activeDirSync )
0 commit comments