private async Task BackupFileAsync(string localFilePath, CancellationToken stoppingToken) { using IServiceScope scope = _serviceScopeFactory.CreateScope(); var ftpClient = scope.ServiceProvider.GetRequiredService <FtpClient>(); await ftpClient.ConnectAsync(stoppingToken); FileInfo fileInfo = new(localFilePath); string remoteFilePath = Path.Combine(_options.RemotePath, fileInfo.Name); FtpStatus status = await ftpClient.UploadFileAsync(localFilePath, remoteFilePath, token : stoppingToken); Action afterUploadAction = status switch { FtpStatus.Failed => () => _logger.LogInformation($"The file {fileInfo.Name} upload failed with an error transfering, or the source file did not exist"), FtpStatus.Success => () => { _logger.LogInformation($"File {fileInfo.Name} uploaded."); DeleteLocalFile(fileInfo); }, _ => () => { } }; afterUploadAction(); }
private FtpStatus SendCommand(bool waitResponse, string command, params string[] parameters) { byte[] cmd; string commandString = command; if (parameters.Length > 0) { commandString += " " + String.Join(" ", parameters); } commandString += EOL; cmd = Encoding.ASCII.GetBytes(commandString); try { controlStream.Write(cmd, 0, cmd.Length); } catch (IOException) { //controlStream.Close (); return(new FtpStatus(FtpStatusCode.ServiceNotAvailable, "Write failed")); } if (!waitResponse) { return(null); } FtpStatus result = GetResponseStatus(); if (ftpResponse != null) { ftpResponse.UpdateStatus(result); } return(result); }
/// <summary> /// 下载单文件 /// </summary> /// <param name="localDic">本地目录(@"D:\test")</param> /// <param name="remotePath">远程路径("/test/abc.txt")</param> /// <returns></returns> public FtpStatus DownloadFile(string localDic, string remotePath) { FtpStatus boolResult = FtpStatus.Failed; string strFileName = string.Empty; try { //本地目录不存在,则自动创建 if (!Directory.Exists(localDic)) { Directory.CreateDirectory(localDic); } //取下载文件的文件名 strFileName = Path.GetFileName(remotePath); //拼接本地路径 localDic = Path.Combine(localDic, strFileName); if (Connect()) { boolResult = ftpClient.DownloadFile(localDic, remotePath, FtpLocalExists.Overwrite); } } catch (Exception ex) { NLog.LogManager.GetCurrentClassLogger().Error("DownloadFile->下载文件 异常:" + ex.ToString() + "|*|remotePath:" + remotePath); } finally { DisConnect(); } return(boolResult); }
private static string GetInitialPath(FtpStatus status) { int s = (int)status.StatusCode; if (s < 200 || s > 300 || status.StatusDescription.Length <= 4) { throw new WebException("Error getting current directory: " + status.StatusDescription, null, WebExceptionStatus.UnknownError, null); } string msg = status.StatusDescription.Substring(4); if (msg[0] == '"') { int next_quote = msg.IndexOf('\"', 1); if (next_quote == -1) { throw new WebException("Error getting current directory: PWD -> " + status.StatusDescription, null, WebExceptionStatus.UnknownError, null); } msg = msg.Substring(1, next_quote - 1); } if (!msg.EndsWith("/")) { msg += "/"; } return(msg); }
/// <summary> /// 上传多文件 /// </summary> /// <param name="localFiles">本地路径列表</param> /// <param name="remoteDic">远端目录("/test")</param> /// <returns></returns> public FluentFTP.FtpStatus UploadFiles(IEnumerable <string> localFiles, string remoteDic) { FtpStatus ftpStatus = FtpStatus.Failed; int count = 0; List <FileInfo> listFiles = new List <FileInfo>(); if (localFiles == null) { return(0); } try { foreach (string file in localFiles) { if (!File.Exists(file)) { NLog.LogManager.GetCurrentClassLogger().Error("UploadFiles->本地文件不存在:" + file); continue; } listFiles.Add(new FileInfo(file)); } //远端路径校验 if (string.IsNullOrEmpty(remoteDic)) { remoteDic = "/"; } if (!remoteDic.StartsWith("/")) { remoteDic = "/" + remoteDic; } if (!remoteDic.EndsWith("/")) { remoteDic += "/"; } if (Connect()) { if (listFiles.Count > 0) { count = ftpClient.UploadFiles(listFiles, remoteDic, FtpRemoteExists.Overwrite, true); } } } catch (Exception ex) { NLog.LogManager.GetCurrentClassLogger().Error("UploadFiles->上传文件 异常:" + ex.ToString()); } finally { DisConnect(); } if (count > 0) { return(FtpStatus.Success); } return(ftpStatus); }
public override bool SendFile(string SourceFilePath, string FilePath) { BVM.SetSize(String.Format("Current File Size : {0}", WriterOperations.BytesToString(new FileInfo(SourceFilePath).Length))); Log.Debug(String.Format("Updating File {0} - {1}", SourceFilePath, FilePath)); FtpStatus Status = Client.UploadFile(SourceFilePath, FilePath, FtpRemoteExists.Overwrite, true, FtpVerify.None, Progress); return(Status.IsSuccess()); }
private Exception CreateExceptionFromResponse(FtpStatus status) { FtpWebResponse ftpResponse = new FtpWebResponse(this, requestUri, method, status); WebException exc = new WebException("Server returned an error: " + status.StatusDescription, null, WebExceptionStatus.ProtocolError, ftpResponse); return(exc); }
private static void FtpClientDownload() { FtpClient client = new FtpClient(); client.Host = "192.168.31.30"; client.Credentials = new NetworkCredential("MBaibatyrov", "4R5t6y7u_"); client.Connect(); FtpStatus Status = client.DownloadFile("TCP.pptx.gz", "/sdf/fTCP.pptx.gz"); }
private void InitiateSecureConnection(ref Stream stream) { FtpStatus status = SendCommand(AuthCommand, "TLS"); if (status.StatusCode != FtpStatusCode.ServerWantsSecureSession) { throw CreateExceptionFromResponse(status); } ChangeToSSLSocket(ref stream); }
/// <summary> /// 上传单文件 /// </summary> /// <param name="localPath">本地路径(@"D:\abc.txt")</param> /// <param name="remoteDic">远端目录("/test")</param> /// <returns></returns> public FtpStatus UploadFile(string localPath, string remoteDic) { FtpStatus boolResult = FtpStatus.Failed; FileInfo fileInfo = null; try { //本地路径校验 if (!File.Exists(localPath)) { NLog.LogManager.GetCurrentClassLogger().Error("UploadFile->本地文件不存在:" + localPath); return(boolResult); } else { fileInfo = new FileInfo(localPath); } //远端路径校验 if (string.IsNullOrEmpty(remoteDic)) { remoteDic = "/"; } if (!remoteDic.StartsWith("/")) { remoteDic = "/" + remoteDic; } if (!remoteDic.EndsWith("/")) { remoteDic += "/"; } //拼接远端路径 remoteDic += fileInfo.Name; if (Connect()) { using (FileStream fs = fileInfo.OpenRead()) { //重名覆盖 boolResult = ftpClient.Upload(fs, remoteDic, FtpRemoteExists.Overwrite, true); } } } catch (Exception ex) { NLog.LogManager.GetCurrentClassLogger().Error("UploadFile->上传文件 异常:" + ex.ToString() + "|*|localPath:" + localPath); } finally { DisConnect(); } return(boolResult); }
private void SetType() { if (binary) { FtpStatus status = SendCommand(TypeCommand, DataType); if ((int)status.StatusCode < 200 || (int)status.StatusCode >= 300) { throw CreateExceptionFromResponse(status); } } }
public bool Upload(String localPath, String remotePath) { if (client == null) { return(false); } FtpStatus status = client.UploadFile(localPath, remotePath, FtpRemoteExists.Overwrite, true, FtpVerify.None); if (status.IsFailure()) { } return(status.IsSuccess()); }
// Here we could also get a server error, so be cautious internal void SetTransferCompleted() { if (InFinalState()) { return; } State = RequestState.Finished; FtpStatus status = GetResponseStatus(); ftpResponse.UpdateStatus(status); if (!keepAlive) { CloseConnection(); } }
/// <summary> /// 定时任务 /// </summary> public void circleWork() { string path = Application.StartupPath + "\\imageErrorMess.txt"; List <string> txtList = new List <string>(); try { using (StreamReader sr = new StreamReader(path, Encoding.Default)) { String line; while ((line = sr.ReadLine()) != null && ((line = sr.ReadLine()) != "")) { //根据文本里面的图片路径,并上传到FTP,如果上传失败,则记录到string[]中,并重新给txt赋值 string[] pathArray = line.Split('|'); FtpStatus ftpStatus = FtpHelper.upload(pathArray[0], pathArray[1]); if (ftpStatus == FtpStatus.Success) { FileWorker.LogHelper.WriteLog("上传文件" + pathArray[0] + "成功"); } else if (ftpStatus == FtpStatus.Skipped) { FileWorker.LogHelper.WriteLog("上传文件" + pathArray[0] + "在服务端已存在,跳过传输"); } else { FileWorker.LogHelper.WriteLog("上传文件" + pathArray[0] + "失败"); txtList.Add(pathArray[0] + "|" + pathArray[1]); } } } } catch (Exception ex) { FileWorker.LogHelper.WriteLog("定时任务文件打开报错:" + ex.Message); } string[] arr = ListToArray(txtList); if (arr.Length == 1 && arr[0] == "") { File.WriteAllText(path, ""); } else { File.WriteAllLines(path, arr); } }
public async Task ShouldUploadFileToFtpServerPath() { var ftpClient = new FtpClient("127.0.0.1", "guest", "guest"); var profile = new FtpProfile(); profile.Host = "127.0.0.1"; profile.RetryAttempts = 3; string fileTobeUploaded = @"myDirectory/2.jpg"; var fileInfo = new FileInfo(fileTobeUploaded); using FileStream fileStream = fileInfo.OpenRead(); FtpStatus ftpStatus = await ftpClient.UploadAsync(fileStream, "/myremotpath/"); Assert.True(ftpStatus.IsSuccess()); }
private void ProcessRequest() #endif { if (State == RequestState.Scheduled) { ftpResponse = new FtpWebResponse(this, requestUri, method, keepAlive); try { ProcessMethod(); //State = RequestState.Finished; //finalResponse = ftpResponse; asyncResult.SetCompleted(false, ftpResponse); } catch (Exception e) { if (!GetServicePoint().UsesProxy) { State = RequestState.Error; } SetCompleteWithError(e); } } else { if (InProgress()) { FtpStatus status = GetResponseStatus(); ftpResponse.UpdateStatus(status); if (ftpResponse.IsFinal()) { State = RequestState.Finished; } } asyncResult.SetCompleted(false, ftpResponse); } }
/// <summary> /// Checks if the operation has failed. /// </summary> public static bool IsFailure(this FtpStatus status) { return(status == FtpStatus.Failed); }
public void SetError(string error) { Message = error; Status = FtpStatus.Error; }
public void SetError(string error, params object[] arguments) { Message = string.Format(error, arguments); Status = FtpStatus.Error; }
protected void syncDir( string _localDir, string _remoteDir) { string comparisonFilePath = this.createComparisionFile( _localDir); string comparisonFileRemote = System.IO.Path.Combine( _remoteDir, Constants.comparison_file).Replace( '\\', '/'); // Make sure remote path exists. bool result = this.ftpClient.FileExists( comparisonFileRemote); if (result == false || this.ftpForceCompleteUpload == true) { // Never been synced. Remove and upload all files. FtpListItem[] fileList = this.ftpClient.GetListing( _remoteDir); foreach (FtpListItem f in fileList) { if (f.Type == FtpFileSystemObjectType.File) { string remoteFilePath = System.IO.Path.Combine( _remoteDir, f.Name).Replace( '\\', '/'); this.ftpClient.DeleteFile( remoteFilePath); } } string[] files = System.IO.Directory.GetFiles( _localDir, "", System.IO.SearchOption.TopDirectoryOnly); foreach (string file in files) { string fileName = System.IO.Path.GetFileName(file); string remoteFilePath = System.IO.Path.Combine( _remoteDir, fileName).Replace( '\\', '/'); System.IO.FileStream fs = System.IO.File.OpenRead( file); FtpStatus status = this.ftpClient.Upload( fs, remoteFilePath); fs.Close(); /* * this.ftpClient.UploadFile( * file, * remoteFilePath); */ } } else { // Fetch remote comparision file from FTP and save as "comparison_remote.txt". string comparisonFileLocalRemote = System.IO.Path.Combine( _localDir, Constants.comparison_file_remote); this.ftpClient.DownloadFile( comparisonFileLocalRemote, comparisonFileRemote); Dictionary <string, string> dictLocal = this.convertComparisonFileToDict( comparisonFilePath); Dictionary <string, string> dictRemote = this.convertComparisonFileToDict( comparisonFileLocalRemote); // Get dictionary of files to be written. Dictionary <string, string> dictWrite = this.filesToWrite( dictLocal, dictRemote); // Get dictionary of files to be deleted. Dictionary <string, string> dictDelete = this.filesToDelete( dictLocal, dictRemote); // Upload all files to be added or updated. foreach (KeyValuePair <string, string> entry in dictWrite) { string key = entry.Key; string value = entry.Value; string fileName = System.IO.Path.GetFileName(key); string remoteFilePath = System.IO.Path.Combine( _remoteDir, fileName).Replace( '\\', '/'); System.IO.FileStream fileS = System.IO.File.OpenRead( key); this.ftpClient.Upload( fileS, remoteFilePath); fileS.Close(); /* * this.ftpClient.UploadFile( * key, * remoteFilePath); */ } // Delete all files to be deleted. foreach (KeyValuePair <string, string> entry in dictDelete) { string key = entry.Key; string value = entry.Value; string fileName = System.IO.Path.GetFileName(key); string remoteFilePath = System.IO.Path.Combine( _remoteDir, fileName).Replace( '\\', '/'); this.ftpClient.DeleteFile( remoteFilePath); } System.IO.FileStream fs = System.IO.File.OpenRead( comparisonFilePath); this.ftpClient.Upload( fs, comparisonFileRemote); fs.Close(); /* * this.ftpClient.UploadFile( * comparisonFilePath, * comparisonFileRemote); */ } }
private void Authenticate() { string username = null; string password = null; string domain = null; if (credentials != null) { username = credentials.UserName; password = credentials.Password; domain = credentials.Domain; } if (username == null) { username = "******"; } if (password == null) { password = "******"; } if (!string.IsNullOrEmpty(domain)) { username = domain + '\\' + username; } // Connect to server and get banner message FtpStatus status = GetResponseStatus(); ftpResponse.BannerMessage = status.StatusDescription; if (EnableSsl) { InitiateSecureConnection(ref controlStream); controlReader = new StreamReader(controlStream, Encoding.ASCII); status = SendCommand("PBSZ", "0"); int st = (int)status.StatusCode; if (st < 200 || st >= 300) { throw CreateExceptionFromResponse(status); } // TODO: what if "PROT P" is denied by the server? What does MS do? status = SendCommand("PROT", "P"); st = (int)status.StatusCode; if (st < 200 || st >= 300) { throw CreateExceptionFromResponse(status); } status = new FtpStatus(FtpStatusCode.SendUserCommand, ""); } if (status.StatusCode != FtpStatusCode.SendUserCommand) { throw CreateExceptionFromResponse(status); } status = SendCommand(UserCommand, username); switch (status.StatusCode) { case FtpStatusCode.SendPasswordCommand: status = SendCommand(PasswordCommand, password); if (status.StatusCode != FtpStatusCode.LoggedInProceed) { throw CreateExceptionFromResponse(status); } break; case FtpStatusCode.LoggedInProceed: break; default: throw CreateExceptionFromResponse(status); } ftpResponse.WelcomeMessage = status.StatusDescription; ftpResponse.UpdateStatus(status); }
/// <summary> /// Checks if the operation was successful or skipped (indicating success). /// </summary> public static bool IsSuccess(this FtpStatus status) { return(status == FtpStatus.Success || status == FtpStatus.Skipped); }
/// <summary>Upload the File to Ftp.</summary> /// <param name="objUploadFileDistributionRequest">Input File distribution request.</param> /// <returns>error if any.</returns> internal static string Upload(ref UploadFileDistributionRequest objUploadFileDistributionRequest) { string error = string.Empty; if (objUploadFileDistributionRequest != null && !string.IsNullOrEmpty(objUploadFileDistributionRequest.FtpServerIP) && !string.IsNullOrEmpty(objUploadFileDistributionRequest.FtpUserName) && !string.IsNullOrEmpty(objUploadFileDistributionRequest.FtpPassword) && objUploadFileDistributionRequest.Folder.NbFiles > 0) { foreach (IRemoteFileClass lRemoteFile in objUploadFileDistributionRequest.Folder.FolderFilesList) { if (lRemoteFile.Exists) { /* Testing mode is enable. So, simulate that file was uploaded properly. * * In the future, a better approach might be found. */ if (lRemoteFile.FileType == FileTypeEnum.Undefined && RemoteFileClass.TestingModeEnabled) { FtpStatus ftpStatus = new FtpStatus(); ftpStatus.FileName = lRemoteFile.FilePath; ftpStatus.FtpStatusCode = FtpStatusCode.FileActionOK;; ftpStatus.OperationException = null; ftpStatus.StatusDescription = "OK"; lRemoteFile.FtpStatus = ftpStatus; continue; } DateTime dtTime = DateTime.Now; FtpWebRequest reqFTP = null; try { InitializeFtpRequest(lRemoteFile, objUploadFileDistributionRequest.FtpServerIP, objUploadFileDistributionRequest.FtpDirectory, objUploadFileDistributionRequest.FtpUserName, objUploadFileDistributionRequest.FtpPassword, out reqFTP); } catch (Exception ex) { return(ex.Message); } if (reqFTP != null) { FtpWebResponse response = null; try { using (ManualResetEvent timerEvent = new ManualResetEvent(false)) using (FtpState ftpState = new FtpState()) { ftpState.RemoteFile = lRemoteFile; ftpState.Request = reqFTP; ftpState.Request.Timeout = Timeout.Infinite; UploadFile(ftpState); if (ftpState.Response != null) { response = ftpState.Response; if (response.StatusCode == FtpStatusCode.ServiceNotAvailable || response.StatusCode == FtpStatusCode.ServiceTemporarilyNotAvailable) { if (DateTime.Now.Subtract(dtTime).TotalMinutes > TimeOut) { error = "T2G Ground Server not responding for " + TimeOut + " period uploading terminated"; objUploadFileDistributionRequest.Folder.UploadingState = UploadingStateEnum.Failed; return(error); } } if (response.StatusCode != FtpStatusCode.FileActionOK && response.StatusCode != FtpStatusCode.ClosingData && response.StatusCode != FtpStatusCode.DirectoryStatus && response.StatusCode != FtpStatusCode.FileStatus && response.StatusCode != FtpStatusCode.SystemType && response.StatusCode != FtpStatusCode.SendUserCommand && response.StatusCode != FtpStatusCode.ClosingControl && response.StatusCode != FtpStatusCode.ClosingData && response.StatusCode != FtpStatusCode.PathnameCreated) { lRemoteFile.HasError = true; LogManager.WriteLog(TraceType.INFO, "File upload error, create transfer task. RequestID = " + objUploadFileDistributionRequest.RequestId.ToString() + ", CRCGuid = " + objUploadFileDistributionRequest.Folder.CRCGuid + ", Folder ID = " + objUploadFileDistributionRequest.Folder.FolderId.ToString() + ", FTP error = " + response.StatusCode.ToString(), "Ground.Core.T2G.T2GClient.StartTransferTask", null, EventIdEnum.GroundCore); objUploadFileDistributionRequest.Folder.UploadingState = UploadingStateEnum.Failed; } FtpStatus ftpStatus = new FtpStatus(); ftpStatus.FileName = lRemoteFile.FilePath; ftpStatus.FtpStatusCode = response.StatusCode; ftpStatus.OperationException = null; ftpStatus.StatusDescription = response.StatusDescription; lRemoteFile.FtpStatus = ftpStatus; } else { error = "Can't upload file on T2G Ftp Server. Server is not responding or input file is invalid, check error log."; objUploadFileDistributionRequest.Folder.UploadingState = UploadingStateEnum.Failed; return(error); } } } catch (Exception ex) { response = (FtpWebResponse)reqFTP.GetResponse(); if (response != null) { FtpStatus ftpStatus = new FtpStatus(); ftpStatus.FileName = lRemoteFile.FilePath; ftpStatus.FtpStatusCode = response.StatusCode; ftpStatus.OperationException = ex; ftpStatus.StatusDescription = response.StatusDescription; lRemoteFile.FtpStatus = ftpStatus; LogManager.WriteLog(TraceType.ERROR, PIS.Ground.Core.Properties.Resources.ExFtpError, "PIS.Ground.Core.Utility.Upload", ex, EventIdEnum.GroundCore); } } finally { if (response != null) { response.Close(); } } } } else { error = "File " + lRemoteFile.FilePath + " does not exist."; return(error); } } } else { error = "Invalid Input parameter"; } return(error); }
internal void UpdateStatus(FtpStatus status) { statusCode = status.StatusCode; statusDescription = status.StatusDescription; }
internal FtpWebResponse(FtpWebRequest request, Uri uri, string method, FtpStatus status) : this(request, uri, method, status.StatusCode, status.StatusDescription) { }
protected override void DefWndProc(ref System.Windows.Forms.Message m) { switch (m.Msg) { case WM_COPYDATA: COPYDATASTRUCT mystr = new COPYDATASTRUCT(); Type mytype = mystr.GetType(); mystr = (COPYDATASTRUCT)m.GetLParam(mytype); string[] messColl = mystr.lpData.Split(new char[] { '=' }); if (messColl[0] == "D00") { //MessageBox.Show(mystr.lpData); FileWorker.LogHelper.WriteLog("接受车底信息记录D00:" + mystr.lpData); MessCommand messComm = Utils.ParseCarScanMess(messColl); string jsonMess = messComm.toJson(); KafkaWorker.sendCarRecordMessage(jsonMess); Task.Run(() => { //在上传图片之前先进行压缩,保存到本地上,然后拿到压缩后的路径,进行FTP的上传 //string path = string.Format("/{0}/{1}", DateTime.Now.ToString("yyyy.MM.dd"), Path.GetFileName(messComm.body.vechicleInUvssPicpath)); FtpStatus ftpStatus = FtpHelper.upload(messColl[4], messComm.body.vechicleInUvssPicpath); if (ftpStatus == FtpStatus.Success) { FileWorker.LogHelper.WriteLog("上传文件" + messColl[4] + "成功"); } else if (ftpStatus == FtpStatus.Skipped) { FileWorker.LogHelper.WriteLog("上传文件" + messColl[4] + "在服务端已存在,跳过传输"); } else { FileWorker.LogHelper.WriteLog("上传文件" + messColl[4] + "失败"); string txtPath = Application.StartupPath + "\\imageErrorMess.txt"; string txt = string.Format("{0}|{1}", messColl[4], messComm.body.vechicleInUvssPicpath); WriteLogFile(txtPath, txt); } //string txtPath = Application.StartupPath + "\\imageErrorMess.txt"; //string txt = string.Format("{0}|{1}", messComm.body.vechicleInUvssPicpath, path); //WriteLogFile(txtPath, txt); }); } else if (messColl[0] == "D01") { //FileWorker.LogHelper.WriteLog("基本工作状态D01:" + mystr.lpData); //WorkingState work = Utils.ParseWorkMess(messColl); //string jsonMess = work.toJson(); //KafkaTest.SendMessCommand(jsonMess); } else if (messColl[0] == "D02") { FileWorker.LogHelper.WriteLog("第3方自定义功能D02:" + mystr.lpData); if (messColl[1] == "0") { this.Close(); } else if (messColl[1] == "1") { this.TopMost = true; } else if (messColl[1] == "2") //D02 = 2 = N = EOF { //N 最大接入许可数量 //MessageOrder work = Utils.ParseMessOrder(messColl); //上行,发送"U02=2=EOF" SendResponOrder(); } else { } } else { FileWorker.LogHelper.WriteLog("未知命令:" + mystr.lpData); //MessageBox.Show(mystr.lpData); } break; default: base.DefWndProc(ref m); break; } }
private void OpenControlConnection() { Exception exception = null; #if SSHARP CrestronClientSocket sock = null; #else Socket sock = null; #endif foreach (IPAddress address in hostEntry.AddressList) { #if SSHARP #if !IPV6 if (address.AddressFamily == AddressFamily.InterNetworkV6) { continue; } #endif sock = new CrestronClientSocket(); #else sock = new Socket(address.AddressFamily, SocketType.Stream, ProtocolType.Tcp); #endif IPEndPoint remote = new IPEndPoint(address, requestUri.Port); if (!ServicePoint.CallEndPointDelegate(sock, remote)) { sock.Close(); sock = null; } else { try { sock.Connect(remote); localEndPoint = (IPEndPoint)sock.LocalEndPoint; break; } catch (SocketException exc) { exception = exc; sock.Close(); sock = null; } } } // Couldn't connect to any address if (sock == null) { throw new WebException("Unable to connect to remote server", exception, WebExceptionStatus.UnknownError, ftpResponse); } controlStream = new NetworkStream(sock); controlReader = new StreamReader(controlStream, Encoding.ASCII); State = RequestState.Authenticating; Authenticate(); FtpStatus status = SendCommand("OPTS", "utf8", "on"); // ignore status for OPTS status = SendCommand(WebRequestMethods.Ftp.PrintWorkingDirectory); initial_path = GetInitialPath(status); }