Many modern FTP servers support determining checksums (CRC-32, MD5 or SHA-1) of remote files. You can use Ftp
object's GetSupportedChecksumTypes
method to determine whether the FTP server support this functionality (and which algorithms). If it does, use GetRemoteChecksum
method to get a checksum of a file at the server or a specified part of it. The corresponding checksums of local files can be calculated using Ftp.CalculateLocalChecksum
static method. Not all FTP servers support this, unfortunately.
An alternative is FTP/SSL. SSL has built-in integrity checking (either using MD5 or SHA1) and should never transfer a damaged data packet.
Also, make sure to check that the file lengths of local and remote files are the same before determining any checksums. If they aren't, they will never match.
Here is a sample code:
//create FTP client
Ftp client = new Ftp();
//Connect to the FTP server
client.Connect(hostname, port);
//authorize to the server
client.Login(login, password);
//upload a file
long uploadLength = client.PutFile(localPath, remotePath);
// get the remote file length
long remoteLength = client.GetFileLength(remotePath);
// get the local file length
long localLength = new System.IO.FileInfo(localPath).Length;
//check file lengths
if (uploadLength != localLength || remoteLength != localLength)
throw new Exception("File lengths differ.");
//get checksums supported by the server
FtpChecksumType[] checksums = client.GetSupportedChecksumTypes();
//check the checksum of local and remote file
if (checksums.Length > 0)
{
string remoteChecksum = client.GetRemoteChecksum(checksums[0], remotePath);
string localChecksum = Ftp.CalculateLocalChecksum(checksums[0], localPath);
if (remoteChecksum != localChecksum)
throw new Exception("File checksums differ.");
}
else
{
throw new Exception("Server does not support checksum");
}