/// <summary> Descargar un fichero al servidor Ftp. </summary> /// /// <param name="remoteFile"> Nombre del fichero remoto. </param> /// <param name="localFile"> Nombre del fichero local. </param> /// <param name="crearFichero"> Sobreescribir destino si ya existe. </param> /// /// <returns> Resultado (S/N/C) </returns> /// public Char FtpDownloadFile(string remoteFile, string localFile, int crearFichero = (int)FileMode.Create) { FileStream localFileStream; byte[] byteBuffer; int bytesLeidos; Resultado = 'N'; try { if (String.IsNullOrEmpty(FTPHost) || string.IsNullOrEmpty(FTPUser) || FTPPwd == null) { UsrError = "KO - Faltan parámetros de conexión al Host Ftp"; UsrErrorC = -1; Resultado = 'N'; return(Resultado); } // Conexión con el Host Ftp. FtpRequest = (FtpWebRequest)FtpWebRequest.Create(FTPHost + "/" + remoteFile); FtpRequest.Credentials = new NetworkCredential(FTPUser, FTPPwd); FtpRequest.Method = WebRequestMethods.Ftp.DownloadFile; // Canal de comunicación con el Host Ftp. FtpResponse = (FtpWebResponse)FtpRequest.GetResponse(); // Retorno de comunicación con el Host Ftp. FtpFileStream = FtpResponse.GetResponseStream(); // Canal de comunicación con el fichero local. localFileStream = new FileStream(localFile, FileMode.Create); byteBuffer = new byte[_BYTE_BUFFER]; // Leer datos del fichero remoto y grabar en fichero local. bytesLeidos = FtpFileStream.Read(byteBuffer, 0, _BYTE_BUFFER); while (bytesLeidos > 0) { localFileStream.Write(byteBuffer, 0, _BYTE_BUFFER); bytesLeidos = FtpFileStream.Read(byteBuffer, 0, _BYTE_BUFFER); } // Cerrar canales de comunicación Ftp. localFileStream.Close(); FtpFileStream.Close(); FtpRequest = null; FtpResponse.Close(); Resultado = 'S'; UsrError = "OK"; } catch (Exception ex) { // Error de Ftp. UsrErrorC = ex.HResult; UsrError = ex.Message; UsrErrorE = ex.StackTrace; Resultado = 'C'; } return(Resultado); }
/// <summary> /// Compare the specified local file with the remote file on the FTP server using various kinds of quick equality checks. /// In Auto mode, the file size and checksum are compared. /// Comparing the checksum of a file is a quick way to check if the contents of the files are exactly equal without downloading a copy of the file. /// You can use the option flags to compare any combination of: file size, checksum, date modified. /// </summary> /// <param name="localPath">The full or relative path to the file on the local file system</param> /// <param name="remotePath">The full or relative path to the file on the server</param> /// <param name="options">Types of equality checks to perform. Use Auto to compare file size and checksum.</param> /// <returns></returns> public FtpCompareResult CompareFile(string localPath, string remotePath, FtpCompareOption options = FtpCompareOption.Auto) { // verify args if (localPath.IsBlank()) { throw new ArgumentException("Required parameter is null or blank.", "localPath"); } if (remotePath.IsBlank()) { throw new ArgumentException("Required parameter is null or blank.", "remotePath"); } LogFunc(nameof(CompareFile), new object[] { localPath, remotePath, options }); // ensure both files exists if (!File.Exists(localPath)) { return(FtpCompareResult.FileNotExisting); } if (!FileExists(remotePath)) { return(FtpCompareResult.FileNotExisting); } // if file size check enabled if (options == FtpCompareOption.Auto || options.HasFlag(FtpCompareOption.Size)) { // check file size var localSize = FtpFileStream.GetFileSize(localPath, false); var remoteSize = GetFileSize(remotePath); if (localSize != remoteSize) { return(FtpCompareResult.NotEqual); } } // if date check enabled if (options.HasFlag(FtpCompareOption.DateModified)) { // check file size var localDate = FtpFileStream.GetFileDateModifiedUtc(localPath); var remoteDate = GetModifiedTime(remotePath, FtpDate.UTC); if (!localDate.Equals(remoteDate)) { return(FtpCompareResult.NotEqual); } } // if checksum check enabled if (options == FtpCompareOption.Auto || options.HasFlag(FtpCompareOption.Checksum)) { // check file checksum if (SupportsChecksum()) { var hash = GetChecksum(remotePath); if (hash.IsValid) { if (!hash.Verify(localPath)) { return(FtpCompareResult.NotEqual); } } else { return(FtpCompareResult.ChecksumNotSupported); } } else { return(FtpCompareResult.ChecksumNotSupported); } } // all checks passed! return(FtpCompareResult.Equal); }
//------------------------------------------------------------------ // Métodos públicos de la clase. //------------------------------------------------------------------ /// <summary> /// /// </summary> /// <param name="remoteFile"> Nombre del fichero remoto. </param> /// /// <returns> Resultado (S/N/C) </returns> /// public Char FtpFileExists(string remoteFile) { // string fileInfo; Innecesario. Resultado = 'N'; try { if (String.IsNullOrEmpty(FTPHost) || string.IsNullOrEmpty(FTPUser) || FTPPwd == null) { UsrError = "KO - Faltan parámetros de conexión al Host Ftp"; UsrErrorC = -1; Resultado = 'N'; return(Resultado); } FtpRequest = (FtpWebRequest)FtpWebRequest.Create(FTPHost + "/" + remoteFile); FtpRequest.Credentials = new NetworkCredential(FTPUser, FTPPwd); FtpRequest.Method = WebRequestMethods.Ftp.GetDateTimestamp; // Canal de comunicación con el Host Ftp. FtpResponse = (FtpWebResponse)FtpRequest.GetResponse(); // Retorno de comunicación con el Host Ftp. FtpFileStream = FtpResponse.GetResponseStream(); // Canal de lectura del Host Ftp. - Innecesario. // FtpStreamReader = new StreamReader(FtpFileStream); // fileInfo = FtpStreamReader.ReadToEnd(); // Cerrar canales de comunicación Ftp. FtpFileStream.Close(); FtpRequest = null; FtpResponse.Close(); Resultado = 'S'; UsrError = "OK"; } catch (WebException ex) when(ex.Status.ToString() == "ProtocolError") { // Error de Ftp. UsrErrorC = ex.HResult; UsrError = ex.Message; UsrErrorE = ex.StackTrace; Resultado = 'N'; } catch (Exception ex) { // Error de programa. UsrErrorC = ex.HResult; UsrError = ex.Message; UsrErrorE = ex.StackTrace; Resultado = 'C'; } return(Resultado); }
/// <summary> /// Compare the specified local file with the remote file on the FTP server using various kinds of quick equality checks. /// In Auto mode, the file size and checksum are compared. /// Comparing the checksum of a file is a quick way to check if the contents of the files are exactly equal without downloading a copy of the file. /// You can use the option flags to compare any combination of: file size, checksum, date modified. /// </summary> /// <param name="localPath">The full or relative path to the file on the local file system</param> /// <param name="remotePath">The full or relative path to the file on the server</param> /// <param name="options">Types of equality checks to perform. Use Auto to compare file size and checksum.</param> /// <param name="token">The token that can be used to cancel the entire process</param> /// <returns></returns> public async Task <FtpCompareResult> CompareFileAsync(string localPath, string remotePath, FtpCompareOption options = FtpCompareOption.Auto, CancellationToken token = default(CancellationToken)) { // verify args if (localPath.IsBlank()) { throw new ArgumentException("Required parameter is null or blank.", "localPath"); } if (remotePath.IsBlank()) { throw new ArgumentException("Required parameter is null or blank.", "remotePath"); } remotePath = remotePath.GetFtpPath(); LogFunc(nameof(CompareFileAsync), new object[] { localPath, remotePath, options }); // ensure both files exists if (!File.Exists(localPath)) { return(FtpCompareResult.FileNotExisting); } if (!await FileExistsAsync(remotePath, token)) { return(FtpCompareResult.FileNotExisting); } // if file size check enabled if (options == FtpCompareOption.Auto || options.HasFlag(FtpCompareOption.Size)) { // check file size var localSize = await FtpFileStream.GetFileSizeAsync(localPath, false, token); var remoteSize = await GetFileSizeAsync(remotePath, -1, token); if (localSize != remoteSize) { return(FtpCompareResult.NotEqual); } } // if date check enabled if (options.HasFlag(FtpCompareOption.DateModified)) { // check file size var localDate = await FtpFileStream.GetFileDateModifiedUtcAsync(localPath, token); var remoteDate = await GetModifiedTimeAsync(remotePath, token); if (!localDate.Equals(remoteDate)) { return(FtpCompareResult.NotEqual); } } // if checksum check enabled if (options == FtpCompareOption.Auto || options.HasFlag(FtpCompareOption.Checksum)) { // check file checksum if (SupportsChecksum()) { var hash = await GetChecksumAsync(remotePath, FtpHashAlgorithm.NONE, token); if (hash.IsValid) { if (!hash.Verify(localPath)) { return(FtpCompareResult.NotEqual); } } else { return(FtpCompareResult.ChecksumNotSupported); } } else { return(FtpCompareResult.ChecksumNotSupported); } } // all checks passed! return(FtpCompareResult.Equal); }