/// <summary> /// Obtains a response stream as a string /// </summary> /// <param name="ftp">current FTP request</param> /// <returns>String containing response</returns> /// <remarks>FTP servers typically return strings with CR and /// not CRLF. Use respons.Replace(vbCR, vbCRLF) to convert /// to an MSDOS string</remarks> private string GetStringResponse(FtpWebRequest ftp) { //Get the result, streaming to a string string result = ""; using (FtpWebResponse response = (FtpWebResponse)ftp.GetResponse()) { long size = response.ContentLength; using (Stream datastream = response.GetResponseStream()) { using (StreamReader sr = new StreamReader(datastream)) { _WelcomeMessage = response.WelcomeMessage; _ExitMessage = response.ExitMessage; result = sr.ReadToEnd(); sr.Close(); } try { //Declare Event NewMessageEventArgs e = new NewMessageEventArgs("RESPONSE", response.StatusDescription, response.StatusCode.ToString()); //Raise Event //OnNewMessageReceived(this, e); } catch { } datastream.Close(); } response.Close(); } return(result); }
/// <summary> /// 디렉토리 전체를 삭제 /// </summary> /// <param name="dirpath">파일이 존재하는 디렉토리 (DONGSHIN 이하 전부 기입)</param> /// <returns></returns> /// <remarks></remarks> public bool DeleteDirectory(string dirpath) { try { //실제로 디렉토리가 존재하면 삭제 실행 if (IsExtistDirectory(dirpath)) { //디렉토리 안에 파일이 존재하면 삭제 후 디렉토리 삭제 List <string> fileNameList = new List <string>(); fileNameList = GetFileNameList(dirpath); if (fileNameList.Count > 0) { for (int i = 0; i < fileNameList.Count; i++) { DeleteFile(string.Format("{0}/{1}", dirpath, fileNameList[i])); } } string URI = this.Host + AdjustDir(dirpath); System.Net.FtpWebRequest ftp = GetRequest(URI); ftp.Method = System.Net.WebRequestMethods.Ftp.RemoveDirectory; //get response but ignore it string str = GetStringResponse(ftp); //Give Message of Command NewMessageEventArgs e = new NewMessageEventArgs("COMMAND", "Remove Directory", "RMD"); //OnNewMessageReceived(this, e); } } catch (Exception) { return(false); } return(true); }
/// <summary> /// Return a detailed directory listing /// </summary> /// <param name="directory">Directory to list, e.g. /pub/etc</param> /// <returns>An FTPDirectory object</returns> public FTPdirectory ListDirectoryDetail(string directory) { System.Net.FtpWebRequest ftp = GetRequest(GetDirectory(directory)); //Set request to do simple list ftp.Method = System.Net.WebRequestMethods.Ftp.ListDirectoryDetails; //Give Message of Command NewMessageEventArgs e = new NewMessageEventArgs("COMMAND", "List Directory Details", "LIST"); //OnNewMessageReceived(this, e); string str = GetStringResponse(ftp); //replace CRLF to CR, remove last instance str = str.Replace("\r\n", "\r").TrimEnd('\r'); //split the string into a list return(new FTPdirectory(str, _lastDirectory)); }
public bool FtpRename(string sourceFilename, string newName) { //Does file exist? string source = GetFullPath(sourceFilename); if (!FtpFileExists(source)) { throw (new FileNotFoundException("File " + source + " not found")); } //build target name, ensure it does not exist string target = GetFullPath(newName); if (target == source) { throw (new ApplicationException("Source and target are the same")); } else if (FtpFileExists(target)) { throw (new ApplicationException("Target file " + target + " already exists")); } //perform rename string URI = this.Hostname + source; System.Net.FtpWebRequest ftp = GetRequest(URI); //Set request to delete ftp.Method = System.Net.WebRequestMethods.Ftp.Rename; ftp.RenameTo = target; try { //get response but ignore it string str = GetStringResponse(ftp); //Give Message of Command NewMessageEventArgs e = new NewMessageEventArgs("COMMAND", "File Rename", "RENAME"); //OnNewMessageReceived(this, e); } catch (Exception) { return(false); } return(true); }
/// <summary> /// Return a simple directory listing /// </summary> /// <param name="directory">Directory to list, e.g. /pub</param> /// <returns>A list of filenames and directories as a List(of String)</returns> /// <remarks>For a detailed directory listing, use ListDirectoryDetail</remarks> public List <string> ListDirectory(string directory) { //return a simple list of filenames in directory System.Net.FtpWebRequest ftp = GetRequest(GetDirectory(directory)); //Set request to do simple list ftp.Method = System.Net.WebRequestMethods.Ftp.ListDirectory; //Give Message of Command NewMessageEventArgs e = new NewMessageEventArgs("COMMAND", "List Directory", "NLST"); //OnNewMessageReceived(this, e); string str = GetStringResponse(ftp); //replace CRLF to CR, remove last instance str = str.Replace("\r\n", "\r").TrimEnd('\r'); //split the string into a list List <string> result = new List <string>(); result.AddRange(str.Split('\r')); return(result); }
public bool FtpDeleteDirectory(string dirpath) { //perform remove string URI = this.Hostname + AdjustDir(dirpath); System.Net.FtpWebRequest ftp = GetRequest(URI); //Set request to RmDir ftp.Method = System.Net.WebRequestMethods.Ftp.RemoveDirectory; try { //get response but ignore it string str = GetStringResponse(ftp); //Give Message of Command NewMessageEventArgs e = new NewMessageEventArgs("COMMAND", "Remove Directory", "RMD"); //OnNewMessageReceived(this, e); } catch (Exception) { return(false); } return(true); }
/// <summary> /// Delete remote file /// </summary> /// <param name="filename">filename or full path</param> /// <returns></returns> /// <remarks></remarks> public bool FtpDelete(string filename) { //Determine if file or full path string URI = this.Hostname + GetFullPath(filename); System.Net.FtpWebRequest ftp = GetRequest(URI); //Set request to delete ftp.Method = System.Net.WebRequestMethods.Ftp.DeleteFile; try { //get response but ignore it string str = GetStringResponse(ftp); //Give Message of Command NewMessageEventArgs e = new NewMessageEventArgs("COMMAND", "Delete File", "DELE"); //OnNewMessageReceived(this, e); } catch (Exception) { return(false); } return(true); }
/// <summary> /// Determine size of remote file /// </summary> /// <param name="filename"></param> /// <returns></returns> /// <remarks>Throws an exception if file does not exist</remarks> public long GetFileSize(string filename) { string path; if (filename.Contains("/")) { path = AdjustDir(filename); } else { path = this.CurrentDirectory + filename; } string URI = this.Hostname + path; System.Net.FtpWebRequest ftp = GetRequest(URI); //Try to get info on file/dir? ftp.Method = System.Net.WebRequestMethods.Ftp.GetFileSize; string tmp = this.GetStringResponse(ftp); //Give Message of Command NewMessageEventArgs e = new NewMessageEventArgs("COMMAND", "Get File Size", "SIZE"); //OnNewMessageReceived(this, e); return(GetSize(ftp)); }
//Version taking string/FileInfo public bool Download(string sourceFilename, FileInfo targetFI, bool PermitOverwrite) { //1. check target if (targetFI.Exists && !(PermitOverwrite)) { throw (new ApplicationException("Target file already exists")); } //2. check source string target; if (sourceFilename.Trim() == "") { throw (new ApplicationException("File not specified")); } else if (sourceFilename.Contains("/")) { //treat as a full path target = AdjustDir(sourceFilename); } else { //treat as filename only, use current directory target = CurrentDirectory + sourceFilename; } string URI = Hostname + target; //3. perform copy DownloadFTPRequest = GetRequest(URI); //Set request to download a file in binary mode DownloadFTPRequest.Method = System.Net.WebRequestMethods.Ftp.DownloadFile; DownloadFTPRequest.UseBinary = true; TargetFileInfo = targetFI; //Give Message of Command FtpConnectEventArgs StartMessage = new FtpConnectEventArgs("COMMAND", "Ftp Connect Start", "CONNECT"); //OnFtpConnected(this, StartMessage); System.Windows.Forms.Application.DoEvents(); //open request and get response stream using (DownloadResponse = (FtpWebResponse)DownloadFTPRequest.GetResponse()) { using (DownloadResponseStream = DownloadResponse.GetResponseStream()) { //System.Security.AccessControl.FileSecurity fileSecurity = new System.Security.AccessControl.FileSecurity(targetFI.FullName, System.Security.AccessControl.AccessControlSections.All); //targetFI.SetAccessControl(fileSecurity); //loop to read & write to file using (DownloadFileStream = new FileStream(targetFI.FullName, FileMode.OpenOrCreate, FileAccess.ReadWrite)) { try { //Give Message of Command FtpConnectEventArgs ConnectMessage = new FtpConnectEventArgs("COMMAND", "Ftp Connected", "CONNECT"); //OnFtpConnected(this, ConnectMessage); //Give Message of Command NewMessageEventArgs e = new NewMessageEventArgs("COMMAND", "Download File", "RETR"); //OnNewMessageReceived(this, e); byte[] buffer = new byte[2048]; int read = 0; Int64 TotalBytesRead = 0; Int64 FileSize = this.GetFileSize(sourceFilename); DownloadCanceled = false; do { if (DownloadCanceled) { NewMessageEventArgs CancelMessage = new NewMessageEventArgs("RESPONSE", "Download Canceled.", "CANCEL"); DownloadCanceled = false; //OnNewMessageReceived(this, CancelMessage); return(false); } read = DownloadResponseStream.Read(buffer, 0, buffer.Length); DownloadFileStream.Write(buffer, 0, read); TotalBytesRead += read; //Declare Event DownloadProgressChangedArgs DownloadProgress = new DownloadProgressChangedArgs(TotalBytesRead, FileSize); //Progress changed, Raise the event. //OnDownloadProgressChanged(this, DownloadProgress); System.Windows.Forms.Application.DoEvents(); } while (!(read == 0)); //Get Message and Raise Event NewMessageEventArgs NewMessageArgs = new NewMessageEventArgs("RESPONSE", DownloadResponse.StatusDescription, DownloadResponse.StatusCode.ToString()); //OnNewMessageReceived(this, NewMessageArgs); //Declare Event DownloadCompletedArgs Args = new DownloadCompletedArgs("Successful", true); //Raise Event //OnDownloadCompleted(this, Args); DownloadResponseStream.Close(); DownloadFileStream.Flush(); DownloadFileStream.Close(); DownloadFileStream = null; DownloadResponseStream = null; } catch (Exception ex) { //catch error and delete file only partially downloaded DownloadFileStream.Close(); //delete target file as it's incomplete targetFI.Delete(); //Decalre Event for Error DownloadCompletedArgs DownloadCompleted = new DownloadCompletedArgs("Error: " + ex.Message, false); //Raise Event //OnDownloadCompleted(this, DownloadCompleted); } } if (DownloadFileStream != null) { DownloadResponseStream.Close(); } } if (DownloadFileStream != null) { DownloadResponse.Close(); } } return(true); }
/// <summary> /// Upload a local file to the FTP server /// </summary> /// <param name="fi">Source file</param> /// <param name="targetFilename">Target filename (optional)</param> /// <returns></returns> public bool Upload(FileInfo fi, string targetFilename) { //copy the file specified to target file: target file can be full path or just filename (uses current dir) //1. check target string target; if (targetFilename.Trim() == "") { //Blank target: use source filename & current dir target = this.CurrentDirectory + fi.Name; } else if (targetFilename.Contains("/")) { //If contains / treat as a full path target = AdjustDir(targetFilename); } else { //otherwise treat as filename only, use current directory target = CurrentDirectory + targetFilename; } string URI = Hostname + target; //perform copy UploadFTPRequest = GetRequest(URI); //Set request to upload a file in binary UploadFTPRequest.Method = System.Net.WebRequestMethods.Ftp.UploadFile; UploadFTPRequest.UseBinary = true; //Notify FTP of the expected size UploadFTPRequest.ContentLength = fi.Length; UploadFileInfo = fi; //create byte array to store: ensure at least 1 byte! const int BufferSize = 2048; byte[] content = new byte[BufferSize - 1 + 1]; int dataRead; //open file for reading using (UploadFileStream = fi.OpenRead()) { try { //open request to send //Give Message of Command FtpConnectEventArgs StartMessage = new FtpConnectEventArgs("COMMAND", "Ftp Connect Start", "CONNECT"); //OnFtpConnected(this, StartMessage); System.Windows.Forms.Application.DoEvents(); using (UploadStream = UploadFTPRequest.GetRequestStream()) { //Give Message of Command FtpConnectEventArgs ConnectMessage = new FtpConnectEventArgs("COMMAND", "Ftp Connected", "CONNECT"); //OnFtpConnected(this, ConnectMessage); //Give Message of Command NewMessageEventArgs e = new NewMessageEventArgs("COMMAND", "Upload File", "STOR"); //OnNewMessageReceived(this, e); //Get File Size Int64 TotalBytesUploaded = 0; Int64 FileSize = fi.Length; do { if (UploadCanceled) { NewMessageEventArgs CancelMessage = new NewMessageEventArgs("RESPONSE", "Upload Canceled.", "CANCEL"); //OnNewMessageReceived(this, CancelMessage); UploadCanceled = false; return(false); } dataRead = UploadFileStream.Read(content, 0, BufferSize); UploadStream.Write(content, 0, dataRead); TotalBytesUploaded += dataRead; //Declare Event UploadProgressChangedArgs DownloadProgress = new UploadProgressChangedArgs(TotalBytesUploaded, FileSize); //Progress changed, Raise the event. //OnUploadProgressChanged(this, DownloadProgress); System.Windows.Forms.Application.DoEvents(); } while (!(dataRead < BufferSize)); //Get Message and Raise Event NewMessageEventArgs UPloadResponse = new NewMessageEventArgs("RESPONSE", "File Uploaded!", "STOR"); //OnNewMessageReceived(this, UPloadResponse); //Declare Event UploadCompletedArgs Args = new UploadCompletedArgs("Successful", true); //Raise Event //OnUploadCompleted(this, Args); UploadStream.Close(); } } catch (Exception ex) { //Declare Event UploadCompletedArgs Args = new UploadCompletedArgs("Error: " + ex.Message, false); //Raise Event OnUploadCompleted(this, Args); } finally { //ensure file closed UploadFileStream.Close(); } } UploadFTPRequest = null; return(true); }