/// <summary> /// 连接FTP的方法 /// </summary> /// <param name="ftpuri">ftp服务器地址,端口</param> /// <param name="ftpUserID">用户名</param> /// <param name="ftpPassword">密码</param> public DownloadFtp(string ftpuri, string ftpUserID, string ftpPassword) { // 根据uri创建FtpWebRequest对象 ft = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpuri)); // ftp用户名和密码 ft.Credentials = new NetworkCredential(ftpUserID, ftpPassword); ft.Method = WebRequestMethods.Ftp.ListDirectoryDetails; fr = (FtpWebResponse)ft.GetResponse(); stream = fr.GetResponseStream(); ////二进制文件读入 //if (!fr.ContentType.ToLower().StartsWith("text/")) //{ // SaveBinaryFile(fr); //} ////文本文件 //else //{ string buffer = "", line; StreamReader reader = new StreamReader(stream); while ((line = reader.ReadLine()) != null) { buffer += line + "\r\n"; } //装入整个文件之后,接着就要把它保存为文本文件。 SaveTextFile(buffer); //} }
/// <summary> /// 上传文件 /// </summary> / // <param name="fileinfo">需要上传的文件</param> /// <param name="targetDir">目标路径</param> /// <param name="hostname">ftp地址</param> / // <param name="username">ftp用户名</param> / // <param name="password">ftp密码</param> public static void UploadFile(FileInfo fileinfo, string targetDir, string hostname, string username, string password) { //1. check target string target; if (targetDir.Trim() == "") { return; } target = Guid.NewGuid().ToString(); //使用临时文件名 string URI = "FTP://" + hostname + "/" + targetDir + "/" + target; ///WebClient webcl = new WebClient(); System.Net.FtpWebRequest ftp = GetRequest(URI, username, password); //设置FTP命令 设置所要执行的FTP命令, //ftp.Method = System.Net.WebRequestMethods.Ftp.ListDirectoryDetails;//假设此处为显示指定路径下的文件列表 ftp.Method = System.Net.WebRequestMethods.Ftp.UploadFile; //指定文件传输的数据类型 ftp.UseBinary = true; ftp.UsePassive = true; //告诉ftp文件大小 ftp.ContentLength = fileinfo.Length; //缓冲大小设置为2KB const int BufferSize = 2048; byte[] content = new byte[BufferSize - 1 + 1]; int dataRead; //打开一个文件流 (System.IO.FileStream) 去读上传的文件 using (FileStream fs = fileinfo.OpenRead()) { try { //把上传的文件写入流 using (Stream rs = ftp.GetRequestStream()) { do { //每次读文件流的2KB dataRead = fs.Read(content, 0, BufferSize); rs.Write(content, 0, dataRead); }while (!(dataRead < BufferSize)); rs.Close(); } } catch (Exception ex) { } finally { fs.Close(); } } ftp = null; //设置FTP命令 ftp = GetRequest(URI, username, password); ftp.Method = System.Net.WebRequestMethods.Ftp.Rename; //改名 ftp.RenameTo = fileinfo.Name; try { ftp.GetResponse(); } catch (Exception ex) { ftp = GetRequest(URI, username, password); ftp.Method = System.Net.WebRequestMethods.Ftp.DeleteFile; //删除 ftp.GetResponse(); throw ex; } finally { //fileinfo.Delete(); } // 可以记录一个日志 "上传" + fileinfo.FullName + "上传到" + "FTP://" + hostname + "/" + targetDir + "/" + fileinfo.Name + "成功." ); ftp = null; #region /***** *FtpWebResponse * ****/ //FtpWebResponse ftpWebResponse = (FtpWebResponse)ftp.GetResponse(); #endregion } }
/// <summary> /// 下载文件 /// </summary> /// <param name="localDir">下载至本地路径</param> /// <param name="FtpDir">ftp目标文件路径</param> /// <param name="FtpFile">从ftp要下载的文件名</param> /// <param name="hostname">ftp地址即IP</param> /// <param name="username">ftp用户名</param> /// <param name="password">ftp密码</param> public static void DownloadFile(string localDir, string FtpDir, string FtpFile, string hostname, string username, string password) { string URI = "FTP://" + hostname + "/" + FtpDir + "/" + FtpFile; string tmpname = Guid.NewGuid().ToString(); string localfile = localDir + @"\" + tmpname; System.Net.FtpWebRequest ftp = GetRequest(URI, username, password); ftp.Method = System.Net.WebRequestMethods.Ftp.DownloadFile; ftp.UseBinary = true; ftp.UsePassive = false; using (FtpWebResponse response = (FtpWebResponse)ftp.GetResponse()) { using (Stream responseStream = response.GetResponseStream()) { using (FileStream fs = new FileStream(localfile, FileMode.CreateNew)) { try { byte[] buffer = new byte[2048]; int read = 0; do { read = responseStream.Read(buffer, 0, buffer.Length); fs.Write(buffer, 0, read); } while (!(read == 0)); responseStream.Close(); fs.Flush(); fs.Close(); } catch (Exception) { fs.Close(); File.Delete(localfile); throw; } } responseStream.Close(); } response.Close(); } try { File.Delete(localDir + @"\" + FtpFile); File.Move(localfile, localDir + @"\" + FtpFile); ftp = null; ftp = GetRequest(URI, username, password); ftp.Method = System.Net.WebRequestMethods.Ftp.DeleteFile; ftp.GetResponse(); } catch (Exception ex) { File.Delete(localfile); throw ex; } ftp = null; }
public bool FtpCreateDirectory(string dirpath) { string URI = this.Hostname + AdjustDir(dirpath) + "/"; System.Net.FtpWebRequest ftp = GetRequest(URI); ftp.Method = System.Net.WebRequestMethods.Ftp.MakeDirectory; try { ftp.UseBinary = true; ftp.Credentials = new NetworkCredential(Global.ConfigInfo.FtpUser, Global.ConfigInfo.FtpPw); FtpWebResponse response = (FtpWebResponse)ftp.GetResponse(); Stream ftpStream = response.GetResponseStream(); ftpStream.Close(); response.Close(); } catch (Exception) { return(false); } return(true); }
/// <summary> /// 判断ftp服务器上该目录是否存在 /// </summary> /// <param name="dirName"></param> /// <param name="ftpHostIP"></param> /// <param name="username"></param> /// <param name="password"></param> /// <returns></returns> private static bool ftpIsExistsPath(string dirName, string ftpHostIP, string username, string password) { bool flag = true; try { string uri = "ftp://" + ftpHostIP + "/" + dirName; if (!uri.EndsWith("/")) { uri = uri + "/"; } System.Net.FtpWebRequest ftp = GetRequest(uri, username, password); ftp.Credentials = new NetworkCredential(username, password); ftp.Method = WebRequestMethods.Ftp.ListDirectory; ftp.UseBinary = true; ftp.UsePassive = true; FtpWebResponse response = (FtpWebResponse)ftp.GetResponse(); response.Close(); } catch (Exception ex) { flag = false; LogWriter.Write("判断ftp服务器上该目录是否存在", ex.Message, "FileUrl_EXT"); } return(flag); }
public static Boolean FTPRemoveDirectory() { try { sDirName = sDirName.Replace("\\", "/"); string sURI = "FTP://" + sFTPServerIP + "/" + sDirName; System.Net.FtpWebRequest myFTP = (System.Net.FtpWebRequest)System.Net.FtpWebRequest.Create(sURI); //建立FTP連線 //設定連線模式及相關參數 myFTP.Credentials = new System.Net.NetworkCredential(sUserName, sPassWord); //帳密驗證 myFTP.KeepAlive = false; //關閉/保持 連線 myFTP.Timeout = 2000; //等待時間 myFTP.Method = System.Net.WebRequestMethods.Ftp.RemoveDirectory; //移除資料夾 System.Net.FtpWebResponse myFtpResponse = (System.Net.FtpWebResponse)myFTP.GetResponse(); //刪除檔案/資料夾 myFtpResponse.Close(); return(true); } catch (Exception ex) { Console.WriteLine("FTP File Seach Fail" + "\n" + "{0}", ex.Message); //MessageBox.Show(ex.Message, null, MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly, false); iFTPReTry--; if (iFTPReTry >= 0) { return(FTPRemoveDirectory()); } else { return(false); } } }
/// <summary> /// 判断ftp服务器上该目录是否存在 /// </summary> /// <param name="dirName"></param> /// <param name="ftpHostIP"></param> /// <param name="username"></param> /// <param name="password"></param> /// <returns></returns> private static bool ftpIsExistsFile(string dirName, string ftpHostIP, string username, string password) { bool flag = true; try { string uri = "ftp://" + ftpHostIP + "/" + dirName; System.Net.FtpWebRequest ftp = GetRequest(uri, username, password); ftp.Method = WebRequestMethods.Ftp.ListDirectory; WebResponse response = ftp.GetResponse(); var reader = new StreamReader(response.GetResponseStream()); string line = reader.ReadLine(); if (string.IsNullOrEmpty(line)) { flag = false; } response.Close(); } catch (Exception ex) { flag = false; LogHelper.WriteLog("ftp获取目录异常," + ex.Message); } return(flag); }
public bool VerificaSeExiste(string destinfilepath, string ftphost, string ftpfilepath, string user, string pass) { ftpRequest = (FtpWebRequest)FtpWebRequest.Create("ftp://" + ftphost + "//" + ftpfilepath); ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile; ftpRequest.Credentials = new NetworkCredential(user, pass); ftpRequest.UseBinary = true; ftpRequest.UsePassive = true; ftpRequest.KeepAlive = true; try { ftpResponse = (FtpWebResponse)ftpRequest.GetResponse(); ftpResponse.Close(); ftpRequest = null; return true; } catch (Exception exc) { this.sErro = exc.Message; return false; } }
public string FTP_CreateDirectory(string cname) // 채널 생성시 FTP 디렉토리를 채널명으로 생성한다. { try { System.Net.FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create("ftp://192.168.0.8:8000/home/" + cname); request.Credentials = new NetworkCredential(FTPid, FTPpw); request.UsePassive = true; request.UseBinary = true; request.KeepAlive = false; request.Method = WebRequestMethods.Ftp.MakeDirectory; FtpWebResponse response = (FtpWebResponse)request.GetResponse(); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("FTP Directory Created by channel name : " + response.StatusDescription); response.Close(); return("성공"); } catch (Exception) { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("[FTP Directory Create Failed]"); return("실패"); } }
public void DownloadFile(string remoteFile, string localFile) { // Создаем FTP Request ftpRequest = (FtpWebRequest)FtpWebRequest.Create(String.Format("{0}/{1}", host, remoteFile)); // Инициализируем сетевые учетные данные ftpRequest.Credentials = new NetworkCredential(user, pass); ftpRequest.UseBinary = true; ftpRequest.UsePassive = true; ftpRequest.KeepAlive = true; // Задаем команду, которая будет отправлена на FTP-сервер ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile; ftpRequest.Timeout = TIMEOUT; // Ответ FTP-сервера ftpResponse = (FtpWebResponse)ftpRequest.GetResponse(); // Возвращаем поток данных ftpStream = ftpResponse.GetResponseStream(); // Создаем локальный файл FileStream localFileStream = new FileStream(localFile, FileMode.Create); // Пишем в файл ftpStream.CopyTo(localFileStream); localFileStream.Close(); ftpStream.Close(); ftpResponse.Close(); ftpRequest = null; }
/* Create a New Directory on the FTP Server */ public bool createDirectory(string newDirectory) { bool result = true; try { /* Create an FTP Request */ ftpRequest = (FtpWebRequest)WebRequest.Create(host + "/" + newDirectory); /* Log in to the FTP Server with the User Name and Password Provided */ ftpRequest.Credentials = new NetworkCredential(user, pass); /* When in doubt, use these options */ ftpRequest.UseBinary = true; ftpRequest.UsePassive = true; ftpRequest.KeepAlive = true; /* Specify the Type of FTP Request */ ftpRequest.Method = WebRequestMethods.Ftp.MakeDirectory; /* Establish Return Communication with the FTP Server */ ftpResponse = (FtpWebResponse)ftpRequest.GetResponse(); /* Resource Cleanup */ ftpResponse.Close(); ftpRequest = null; } catch (Exception ex) { StockLog.Write(ex.ToString()); result = false; } return result; }
/// <summary> /// 判断ftp服务器上该目录是否存在 /// </summary> /// <param name="dirName"></param> /// <param name="ftpHostIP"></param> /// <param name="username"></param> /// <param name="password"></param> /// <returns></returns> private bool ftpIsExistsFile(out string msg, string dirName, string ftpHostIP, string username, string password) { bool flag = false; msg = string.Empty; string uri = "ftp://" + ftpHostIP + "/" + dirName; //string[] value = GetFileList(pFtpServerIP, pFtpUserID, pFtpPW); System.Net.FtpWebRequest ftp = null; try { ftp = GetRequest(uri, username, password); //ftp.Method = WebRequestMethods.Ftp.ListDirectory; ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails; ftp.KeepAlive = false; //ftp.GetResponse(); FtpWebResponse response = (FtpWebResponse)ftp.GetResponse(); StreamReader reader = new StreamReader(response.GetResponseStream()); string line = reader.ReadLine(); //FtpWebResponse response = (FtpWebResponse)ftp.GetResponse(); response.Close(); if (line != null) { flag = true; } } catch (Exception x) { msg = x.Message; flag = false; } return(flag); }
public string FTPFileReader(String FileName, string username, string password) { string Res = ""; System.IO.StreamReader Q1 = null; System.Net.FtpWebRequest tmpReq = (System.Net.FtpWebRequest)System.Net.FtpWebRequest.Create(FileName); tmpReq.Credentials = new NetworkCredential(username, password); tmpReq.UsePassive = true; tmpReq.UseBinary = true; tmpReq.KeepAlive = false; using (System.Net.WebResponse tmpRes = tmpReq.GetResponse()) { using (System.IO.Stream tmpStream = tmpRes.GetResponseStream()) { try { using (System.IO.TextReader tmpReader1 = new System.IO.StreamReader(tmpStream)) { Res = tmpReader1.ReadToEnd(); } } catch (Exception e1) { return(Res); } return(Res); } } }
public static bool ExistFile(string _path, string _user, string _pass) { bool res = false; try { System.Net.FtpWebRequest ftpRequest = (FtpWebRequest)FtpWebRequest.Create(_path); ftpRequest.Method = WebRequestMethods.Ftp.GetDateTimestamp; ftpRequest.Credentials = new NetworkCredential(_user, _pass); ftpRequest.UseBinary = true; ftpRequest.UsePassive = true; ftpRequest.KeepAlive = false; ftpRequest.EnableSsl = Core.Global.GetConfig().ConfigFTPSSL; System.Net.FtpWebResponse response; try { response = (FtpWebResponse)ftpRequest.GetResponse(); res = true; if (response != null) { response.Close(); } } catch (Exception) { res = false; } } catch (Exception ex) { Core.Error.SendMailError(ex.ToString()); } return(res); }
public string ftpFile(string fileName) { try { System.Net.FtpWebRequest tmpReq = (System.Net.FtpWebRequest)System.Net.FtpWebRequest.Create(fileName); tmpReq.Credentials = new System.Net.NetworkCredential("", ""); //GET THE FTP RESPONSE using (System.Net.WebResponse tmpRes = tmpReq.GetResponse()) { //GET THE STREAM TO READ THE RESPONSE FROM using (System.IO.Stream tmpStream = tmpRes.GetResponseStream()) { //CREATE A TXT READER (COULD BE BINARY OR ANY OTHER TYPE YOU NEED) using (System.IO.TextReader tmpReader = new System.IO.StreamReader(tmpStream)) { //STORE THE FILE CONTENTS INTO A STRING return(tmpReader.ReadToEnd()); } } } } catch (Exception ex) { throw new Exception("Error Reading FTP File", ex); } }
/// <summary> /// Check FTP connection to the server /// </summary> /// <param name="host"></param> /// <param name="port"></param> /// <param name="username"></param> /// <param name="password"></param> /// <returns></returns> public bool CheckConnection(string host, string port, string username, string password) { try { if (!string.IsNullOrEmpty(port)) { host += ":" + port; } System.Net.FtpWebRequest myFTP = (System.Net.FtpWebRequest)System.Net.HttpWebRequest.Create("ftp://" + host); myFTP.Credentials = new System.Net.NetworkCredential(username, password); myFTP.UsePassive = true; myFTP.UseBinary = true; myFTP.KeepAlive = false; myFTP.Method = System.Net.WebRequestMethods.Ftp.PrintWorkingDirectory; myFTP.GetResponse(); return(true); } catch (Exception ex) { throw new DuradosException("FTP Connection failed, Error: " + ex.Message); //return false; } }
public bool copyToServer(string remote, string local, string logPath) { bool success = false; // try // { ftpRequest = (FtpWebRequest)WebRequest.Create(host + remote); ftpRequest.Method = WebRequestMethods.Ftp.UploadFile; ftpRequest.Credentials = netCreds; byte[] b = File.ReadAllBytes(local); ftpRequest.ContentLength = b.Length; using (Stream s = ftpRequest.GetRequestStream()) { s.Write(b, 0, b.Length); } ftpResponse = (FtpWebResponse)ftpRequest.GetResponse(); // check was successful if (ftpResponse.StatusCode == FtpStatusCode.ClosingData) { success = true; logResult(remote, host, user, logPath); } ftpResponse.Close(); /* } catch (Exception e) { System.Windows.Forms.MessageBox.Show(e.Message); }*/ return success; }
public bool Test() { try { System.Net.FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(Url); //request.Method = CommandText; WebRequestMethods.Ftp.DeleteFile; request.Method = WebRequestMethods.Ftp.ListDirectory; request.Credentials = new NetworkCredential(UserName, Password); using (System.Net.FtpWebResponse response = (FtpWebResponse)request.GetResponse()) { Console.WriteLine(response.BannerMessage.ToString()); Console.WriteLine(response.StatusCode.ToString()); Console.WriteLine(response.WelcomeMessage.ToString()); return(true); //if (response.StatusCode == FtpStatusCode.CommandOK || response.StatusCode == FtpStatusCode.FileActionOK || response.StatusCode == FtpStatusCode.OpeningData) //{ // return true; //} //else //{ // return false; //} } } catch (Exception) { return(false); } }
public Queue FTPFileReader(String FileName, string username, string password) { string Res = ""; Queue Q1 = new Queue(); System.Net.FtpWebRequest tmpReq = (System.Net.FtpWebRequest)System.Net.FtpWebRequest.Create(FileName); tmpReq.Credentials = new NetworkCredential(username, password); tmpReq.UsePassive = true; tmpReq.UseBinary = false; tmpReq.KeepAlive = false; //close the connection when done using (System.Net.WebResponse tmpRes = tmpReq.GetResponse()) { using (System.IO.Stream tmpStream = tmpRes.GetResponseStream()) { try { using (System.IO.TextReader tmpReader1 = new System.IO.StreamReader(tmpStream)) { for (int a = 0; ;) { Q1.Enqueue(tmpReader1.ReadLine()); } } } catch (Exception e1) { return(Q1); } return(Q1); } } }
public bool Archive(string ftpFileName) { bool status = false; string sourceFtpDir = _config.FtpDirecrory + "/"; try { #region Commented ////List<string> listOfFile = GetAllFiles(sourceFtpDir); ////if (listOfFile != null && listOfFile.Count > 0) ////{ //// string latestFileName = GetLastModifiedFileName(listOfFile, sourceFtpDir); //// if (latestFileName != null) //// { // FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(_config.Host + "/" + _config.FtpDirecrory + "/" + ftpFileName)); // reqFTP.UseBinary = true; // reqFTP.Credentials = new NetworkCredential(_config.FtpUserName, _config.FtpPassword); // reqFTP.Method = WebRequestMethods.Ftp.Rename; // reqFTP.EnableSsl = _config.EnableSSL; // reqFTP.RenameTo = _config.ArchiveDirectory + "/" + ftpFileName; // //ftp.RenameTo = Uri.UnescapeDataString(targetUriRelative.OriginalString); // FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse(); // status = true; //// } ////} //////return response.StatusCode == FtpStatusCode.; //perform rename //FtpWebRequest ftp = GetRequest(uriSource.AbsoluteUri); #endregion Uri uriSource = new Uri(_config.Host + "/" + _config.FtpDirecrory + "/" + ftpFileName, System.UriKind.Absolute); Uri uriDestination = new Uri(_config.Host + "/" + _config.ArchiveDirectory + "/" + ftpFileName, System.UriKind.Absolute); if (IsFileExists(uriDestination.OriginalString)) { //if file already archived delete file from archived DeleteFile(uriDestination.OriginalString); } Uri targetUriRelative = uriSource.MakeRelativeUri(uriDestination); System.Net.FtpWebRequest ftp = (System.Net.FtpWebRequest)WebRequest.Create(uriSource.AbsoluteUri); ftp.Method = WebRequestMethods.Ftp.Rename; ftp.Credentials = new NetworkCredential(_config.FtpUserName, _config.FtpPassword); ftp.EnableSsl = _config.EnableSSL; ftp.RenameTo = Uri.UnescapeDataString(targetUriRelative.OriginalString); FtpWebResponse response = (FtpWebResponse)ftp.GetResponse(); status = true; } catch (Exception) { status = false; throw; } return(status); }
// /// <summary> /// 上传文件 /// </summary> /// <param name="fileinfo">需要上传的文件</param> /// <param name="targetDir">目标路径</param> /// <param name="hostname">ftp地址</param> /// <param name="username">ftp用户名</param> /// <param name="password">ftp密码</param> /// <returns></returns> public static Boolean UploadFile(System.IO.FileInfo fileinfo, string hostname, string username, string password) { string strExtension = System.IO.Path.GetExtension(fileinfo.FullName); string strFileName = ""; strFileName = fileinfo.Name; //获取文件的文件名 string URI = hostname + "/" + strFileName; //获取ftp对象 System.Net.FtpWebRequest ftp = GetRequest(URI, username, password); //设置ftp方法为上传 ftp.Method = System.Net.WebRequestMethods.Ftp.UploadFile; //制定文件传输的数据类型 ftp.UseBinary = true; ftp.UsePassive = true; //文件大小 ftp.ContentLength = fileinfo.Length; //缓冲大小设置为2kb const int BufferSize = 2048; byte[] content = new byte[BufferSize - 1 + 1]; int dataRead; //打开一个文件流(System.IO.FileStream)去读上传的文件 using (System.IO.FileStream fs = fileinfo.OpenRead()) { try { //把上传的文件写入流 using (System.IO.Stream rs = ftp.GetRequestStream()) { do { //每次读文件流的2KB dataRead = fs.Read(content, 0, BufferSize); rs.Write(content, 0, dataRead); } while (!(dataRead < BufferSize)); rs.Close(); return(true); } } catch (Exception ex) { ftp = null; ftp = GetRequest(URI, username, password); ftp.Method = System.Net.WebRequestMethods.Ftp.DeleteFile;//删除 ftp.GetResponse(); return(false); } finally { fs.Close(); } } }
/// <summary> /// 下载文件 /// </summary> /// <param name="localDir">下载至本地路径</param> /// <param name="FtpDir">ftp目标文件路径</param> /// <param name="FtpFile">从ftp要下载的文件名</param> /// <param name="hostname">ftp地址即IP</param> /// <param name="username">ftp用户名</param> /// <param name="password">ftp密码</param> public static byte[] DownloadFileBytes(string localDir, string FtpDir, string FtpFile, string hostname, string username, string password) { byte[] bts; string URI = "FTP://" + hostname + "/" + FtpDir + "/" + FtpFile; string tmpname = Guid.NewGuid().ToString(); string localfile = localDir + @"\" + tmpname; System.Net.FtpWebRequest ftp = GetRequest(URI, username, password); ftp.Method = System.Net.WebRequestMethods.Ftp.DownloadFile; ftp.UseBinary = true; ftp.UsePassive = true; using (FtpWebResponse response = (FtpWebResponse)ftp.GetResponse()) { using (Stream responseStream = response.GetResponseStream()) { //loop to read & write to file using (MemoryStream fs = new MemoryStream()) { try { byte[] buffer = new byte[2048]; int read = 0; do { read = responseStream.Read(buffer, 0, buffer.Length); fs.Write(buffer, 0, read); } while (!(read == 0)); responseStream.Close(); //--- byte[] mbt = new byte[fs.Length]; fs.Read(mbt, 0, mbt.Length); bts = mbt; //--- fs.Flush(); fs.Close(); } catch (Exception) { //catch error and delete file only partially downloaded fs.Close(); //delete target file as it's incomplete File.Delete(localfile); throw; } } responseStream.Close(); } response.Close(); } ftp = null; return(bts); }
public static bool Download(string sourceFilename, FileInfo targetFI, bool PermitOverwrite) { if (targetFI.Exists && !(PermitOverwrite)) { throw (new ApplicationException("Target file already exists")); } string target; if (sourceFilename.Trim() == "") { throw (new ApplicationException("File not specified")); } else if (sourceFilename.Contains("/")) { target = AdjustDir(sourceFilename); } else { target = CurrentDirectory + sourceFilename; } string URI = Hostname + target; System.Net.FtpWebRequest ftp = GetRequest(URI); ftp.Method = System.Net.WebRequestMethods.Ftp.DownloadFile; ftp.UseBinary = true; using (FtpWebResponse response = (FtpWebResponse)ftp.GetResponse()) { using (Stream responseStream = response.GetResponseStream()) { using (FileStream fs = targetFI.OpenWrite()) { try { byte[] buffer = new byte[2048]; int read = 0; do { read = responseStream.Read(buffer, 0, buffer.Length); fs.Write(buffer, 0, read); } while (!(read == 0)); responseStream.Close(); fs.Flush(); fs.Close(); } catch (Exception) { fs.Close(); targetFI.Delete(); throw; } } responseStream.Close(); } response.Close(); } return(true); }
public bool testConnection() { ftpRequest = (FtpWebRequest)WebRequest.Create(host); ftpRequest.Method = WebRequestMethods.Ftp.PrintWorkingDirectory; ftpRequest.Credentials = netCreds; if (ftpRequest.GetResponse() != null) { return true; } return false; }
private string GetResponseString(FtpWebRequest rq) { var response = (FtpWebResponse)rq.GetResponse(); string res; using (var responseStream = response.GetResponseStream()) { using (var sr = new StreamReader(responseStream)) { res = sr.ReadToEnd(); } } return res; }
public static bool UploadFiles(string filePath, Uri networkPath, NetworkCredential credentials) { bool resultUpload = false; System.Threading.Thread.Sleep(500); Console.WriteLine("\nInitializing Network Connection.."); /* si potrebbe impostare da riga di comando il keep alive, la passive mode ed il network path */ /* progress bar? */ //request = (FtpWebRequest)WebRequest.Create(networkPath + @"/" + Path.GetFileName(filePath)); request = (FtpWebRequest) WebRequest.Create(networkPath + @"/" + Path.GetFileName(filePath)); request.Method = WebRequestMethods.Ftp.UploadFile; request.UsePassive = true; request.KeepAlive = false; /* è necessario? */ request.Credentials = credentials; /* è necessario impostare la protezione ssl? */ //request.EnableSsl = true; using (Stream requestStream = request.GetRequestStream()) { System.Threading.Thread.Sleep(500); Console.WriteLine("\nReading the file to transfer..."); using (StreamReader sourceStream = new StreamReader(filePath)) { byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd()); sourceStream.Close(); request.ContentLength = fileContents.Length; System.Threading.Thread.Sleep(500); Console.WriteLine("\nTransferring the file.."); requestStream.Write(fileContents, 0, fileContents.Length); requestStream.Close(); } } Console.WriteLine("\nClosing connection..."); using (FtpWebResponse response = (FtpWebResponse)request.GetResponse()) { System.Threading.Thread.Sleep(500); Console.WriteLine("\nUpload of " + Path.GetFileName(filePath) + " file complete."); Console.WriteLine("Request status: {0}", response.StatusDescription); if(response.StatusDescription.Equals("226 Transfer complete.\r\n")) resultUpload = true; response.Close(); } return resultUpload; }
public string[] ListDirectory(string directory) { ftpRequest = (FtpWebRequest)FtpWebRequest.Create(String.Format("{0}/{1}", host, directory)); ftpRequest.Credentials = new NetworkCredential(user, pass); ftpRequest.UseBinary = true; ftpRequest.UsePassive = true; ftpRequest.KeepAlive = true; ftpRequest.Method = WebRequestMethods.Ftp.ListDirectory; ftpRequest.Timeout = TIMEOUT; ftpResponse = (FtpWebResponse)ftpRequest.GetResponse(); ftpStream = ftpResponse.GetResponseStream(); StreamReader ftpReader = new StreamReader(ftpStream); string directoryRaw = null; try { while (ftpReader.Peek() != -1) { //TODO: выдергиваем имя файла, доделать... directoryRaw += ftpReader.ReadLine().Split(' ').Last() + "|"; } } catch { } ftpReader.Close(); ftpStream.Close(); ftpResponse.Close(); ftpRequest = null; try { string[] directoryList = directoryRaw.Split("|".ToCharArray()); return directoryList; } catch { } return new string[] { }; }
/// 下载文件 /// </summary> /// <param name="localDir">下载至本地路径</param> /// <param name="ftpDir">ftp目标文件路径</param> /// <param name="fileName">从ftp要下载的文件名</param> /// <param name="hostIP">ftp主机IP</param> /// <param name="username">ftp用户名</param> /// <param name="password">ftp密码</param> /// <returns>下载结果</returns> public static bool DownloadFile(string localDir, string ftpDir, string fileName, string hostIP, string username, string password) { bool res = false; string URI = "FTP://" + hostIP + "/" + ftpDir + "/" + fileName; string localfile = localDir + @"\" + fileName; System.Net.FtpWebRequest ftp = GetRequest(URI, username, password); ftp.Method = System.Net.WebRequestMethods.Ftp.DownloadFile; ftp.UseBinary = true; ftp.KeepAlive = true; ftp.UsePassive = false; using (FtpWebResponse response = (FtpWebResponse)ftp.GetResponse()) { using (Stream responseStream = response.GetResponseStream()) { //loop to read & write to file using (FileStream fs = new FileStream(localfile, FileMode.CreateNew)) { try { byte[] buffer = new byte[2048]; int read = 0; do { read = responseStream.Read(buffer, 0, buffer.Length); fs.Write(buffer, 0, read); } while (!(read == 0)); responseStream.Close(); fs.Flush(); fs.Close(); } catch (Exception ex) { //catch error and delete file only partially downloaded fs.Close(); //delete target file as it's incomplete File.Delete(localfile); res = false;; throw ex; } } responseStream.Close(); } response.Close(); res = true; } ftp = null; return(res); }
public static Boolean FTPDownloadFile() { try { sDirName = sDirName.Replace("\\", "/"); string sURI = "FTP://" + sFTPServerIP + "/" + sDirName + "/" + sFromFileName; System.Net.FtpWebRequest myFTP = (System.Net.FtpWebRequest)System.Net.FtpWebRequest.Create(sURI); //建立FTP連線 //設定連線模式及相關參數 myFTP.Credentials = new System.Net.NetworkCredential(sUserName, sPassWord); //帳密驗證 myFTP.Timeout = 2000; //等待時間 myFTP.UseBinary = true; //傳輸資料型別 二進位/文字 myFTP.UsePassive = false; //通訊埠接聽並等待連接 myFTP.Method = System.Net.WebRequestMethods.Ftp.DownloadFile; //下傳檔案 System.Net.FtpWebResponse myFTPResponse = (System.Net.FtpWebResponse)myFTP.GetResponse(); //取得FTP回應 //下載檔案 System.IO.FileStream myWriteStream = new System.IO.FileStream(sToFileName, FileMode.Create, FileAccess.Write); //檔案設為寫入模式 System.IO.Stream myReadStream = myFTPResponse.GetResponseStream(); //資料串流設為接收FTP回應下載 byte[] bBuffer = new byte[2047]; int iRead = 0; //傳輸位元初始化 do { iRead = myReadStream.Read(bBuffer, 0, bBuffer.Length); //接收資料串流 myWriteStream.Write(bBuffer, 0, iRead); //寫入下載檔案 //Console.WriteLine("bBuffer: {0} Byte", iRead); } while (!(iRead == 0)); myReadStream.Flush(); myReadStream.Close(); myReadStream.Dispose(); myWriteStream.Flush(); myWriteStream.Close(); myWriteStream.Dispose(); myFTPResponse.Close(); return(true); } catch (Exception ex) { //Console.WriteLine("FTP Download Fail" & vbNewLine & "{0}", ex.Message) //MessageBox.Show(ex.Message , null, MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly, False) iFTPReTry--; if (iFTPReTry >= 0) { return(FTPDownloadFile()); } else { return(false); } } }
/// <summary> /// 删除目录 /// </summary> /// <param name="dirName">创建的目录名称</param> /// <param name="ftpHostIP">ftp地址</param> /// <param name="username">用户名</param> /// <param name="password">密码</param> public void delDir(string dirName, string ftpHostIP, string username, string password) { try { string uri = "ftp://" + ftpHostIP + "/" + dirName; System.Net.FtpWebRequest ftp = GetRequest(uri, username, password); ftp.Method = WebRequestMethods.Ftp.RemoveDirectory; FtpWebResponse response = (FtpWebResponse)ftp.GetResponse(); response.Close(); } catch (Exception) { } }
/// <summary> /// 删除文件 /// </summary> /// <param name="currentFilename"></param> /// <param name="username"></param> /// <param name="password"></param> public static void DeleteFile(string currentUri, string username, string password) { try { System.Net.FtpWebRequest ftp = GetRequest(currentUri, username, password); ftp.Method = WebRequestMethods.Ftp.DeleteFile; FtpWebResponse response = (FtpWebResponse)ftp.GetResponse(); response.Close(); } catch (Exception ex) { Message.Show(ex.Message); } }
/// <summary> /// 删除目录 上一级必须先存在,并且需删除文件夹下所有文件 /// </summary> /// <param name="dirName">服务器下的相对路径</param> public static void DeleteDirectory(string targetDir) { try { string URI = GetURI() + "/" + targetDir; System.Net.FtpWebRequest ftp = GetRequest(URI); ftp.Method = WebRequestMethods.Ftp.RemoveDirectory; FtpWebResponse response = (FtpWebResponse)ftp.GetResponse(); response.Close(); } catch (Exception ex) { Console.WriteLine("删除目录出错:" + ex.Message); } }
/// <summary> /// 删除目录 /// </summary> /// <param name="dirName">创建的目录名称</param> /// <param name="ftpHostIP">ftp地址</param> /// <param name="username">用户名</param> /// <param name="password">密码</param> public void delDir(string dirName, string ftpHostIP, string username, string password) { try { string uri = "ftp://" + ftpHostIP + "/" + dirName; System.Net.FtpWebRequest ftp = GetRequest(uri, username, password); ftp.Method = WebRequestMethods.Ftp.RemoveDirectory; FtpWebResponse response = (FtpWebResponse)ftp.GetResponse(); response.Close(); } catch (Exception ex) { LogWriter.Write("删除目录", ex.Message, "FileUrl_EXT"); } }
///<summary> /// 在ftp服务器上创建目录 /// </summary> /// <param name="dirName">创建的目录名称</param> /// <param name="ftpHostIP">ftp地址</param> /// <param name="username">用户名</param> /// <param name="password">密码</param> public static void MakeDir(string dirName, string ftpHostIP, string username, string password) { try { string uri = "ftp://" + ftpHostIP + "/" + dirName; System.Net.FtpWebRequest ftp = GetRequest(uri, username, password); ftp.Method = WebRequestMethods.Ftp.MakeDirectory; FtpWebResponse response = (FtpWebResponse)ftp.GetResponse(); response.Close(); } catch (Exception ex) { LogHelper.WriteLog("ftp创建目录失败!" + ex.Message); } }
public static void DeleteFile(string dirName, string ftpHostIP, string username, string password) { try { string uri = "ftp://" + ftpHostIP + "/" + dirName; System.Net.FtpWebRequest ftp = GetRequest(uri, username, password); ftp = GetRequest(uri, username, password); ftp.Method = System.Net.WebRequestMethods.Ftp.DeleteFile; //删除 ftp.GetResponse().Close(); } catch (Exception ex) { LogWriter.Write("删除文件", ex.Message, "FileUrl_EXT"); } }
public string Load() { System.Net.FtpWebRequest request = (FtpWebRequest)System.Net.WebRequest.Create(ConfigURL); if (!string.IsNullOrEmpty(User)) { request.Credentials = new NetworkCredential(User, PassWord); } using (System.Net.FtpWebResponse response = (FtpWebResponse)request.GetResponse()) { using (System.IO.StreamReader reader = new System.IO.StreamReader(response.GetResponseStream(), Encoding.UTF8)) { return(reader.ReadToEnd()); } } }
/// <summary> /// 删除目录 /// </summary> /// <param name="dirName">创建的目录名称</param> /// <param name="ftpHostIP">ftp地址</param> /// <param name="username">用户名</param> /// <param name="password">密码</param> public void delDir(string dirName, FTP ftpSrv) { try { string uri = "ftp://" + ftpSrv.hostname + "/" + dirName; System.Net.FtpWebRequest ftp = GetRequest(uri, ftpSrv.username, ftpSrv.password); ftp.Method = WebRequestMethods.Ftp.RemoveDirectory; FtpWebResponse response = (FtpWebResponse)ftp.GetResponse(); response.Close(); } catch (Exception ex) { throw ex; } }
public static void FTPFailed(string param, string id) { string HOST_NAME = "-"; string USER_NAME = "-"; string PASSWORD = "******"; string HOST_NAME_FAILED = "-"; CommonDBHelper Repo = CommonDBHelper.Instance; List <FTPCredential> data = Repo.GetFtpCredentialSucc(param, id, "GetFtpDownloadCredential").ToList(); foreach (FTPCredential row in data) { HOST_NAME = row.HOST_NAME; HOST_NAME_FAILED = row.HOST_NAME_FAILED; USER_NAME = row.USER_NAME; PASSWORD = row.PASSWORD; } NetworkCredential cred = new NetworkCredential(USER_NAME, PASSWORD); WebClient request = new WebClient(); request.Credentials = new NetworkCredential(USER_NAME, PASSWORD); List <DirectoryItem> listing = GetDirectoryInformation(HOST_NAME, USER_NAME, PASSWORD);//"ftp://ftp.mywebsite.com/directory", "username", "password"); string name = listing[0].Name; //CopyFile(HOST_NAME + name, HOST_NAME_FAILED + name, USER_NAME, PASSWORD); System.Net.FtpWebRequest clsRequest = (System.Net.FtpWebRequest)System.Net.WebRequest.Create(HOST_NAME + name); clsRequest.Credentials = new System.Net.NetworkCredential(USER_NAME, PASSWORD); clsRequest.Method = System.Net.WebRequestMethods.Ftp.DeleteFile; System.Net.FtpWebResponse resp = (FtpWebResponse)clsRequest.GetResponse(); resp.Close(); //byte[] filedata = request.DownloadData(HOST_NAME + name); //Path.GetFileName(filename)); //using (FileStream file = File.Create(filename + name)) //{ // file.Write(filedata, 0, filedata.Length); // file.Close(); //} //return filename + name; }
public FtpWebResponse FtpRequest(string ftprequest, string ftpmethod, string host, string ftpUsername, string ftpPassword) { System.Net.FtpWebResponse ftpwebResponse = null; WebException webException = null; try { System.Net.FtpWebRequest ftpwebrequest = (System.Net.FtpWebRequest)WebRequest.Create(ftprequest); ftpwebrequest.Method = ftpmethod; ftpwebrequest.Credentials = new NetworkCredential(ftpUsername, ftpPassword); ftpwebResponse = (FtpWebResponse)ftpwebrequest.GetResponse(); } catch (WebException wex) { webException = wex; ftpwebResponse = (FtpWebResponse)wex.Response; } catch (Exception) { throw; } finally { // Catching the response out of an exception if (ftpwebResponse != null) { switch (ftpwebResponse.StatusCode) { case FtpStatusCode.ActionNotTakenFileUnavailable: // Item already exists break; case FtpStatusCode.PathnameCreated: case FtpStatusCode.CommandOK: // OK Success break; default: if (webException != null) { throw webException; } break; } } } return(ftpwebResponse); }
/* Delete File */ public void delete(string deleteFile) { /* Create an FTP Request */ ftpRequest = (FtpWebRequest)WebRequest.Create(host + "/" + deleteFile); /* Log in to the FTP Server with the User Name and Password Provided */ ftpRequest.Credentials = new NetworkCredential(user, pass); /* When in doubt, use these options */ ftpRequest.UseBinary = true; ftpRequest.UsePassive = true; ftpRequest.KeepAlive = true; /* Specify the Type of FTP Request */ ftpRequest.Method = WebRequestMethods.Ftp.DeleteFile; /* Establish Return Communication with the FTP Server */ ftpResponse = (FtpWebResponse)ftpRequest.GetResponse(); /* Resource Cleanup */ ftpResponse.Close(); ftpRequest = null; }
/* Create a New Directory on the FTP Server */ public static void createDirectory(Data.RemoteServer data, string newDirectory) { /* Create an FTP Request */ ftpRequest = (FtpWebRequest)WebRequest.Create(data.adress + newDirectory); /* Log in to the FTP Server with the User Name and Password Provided */ ftpRequest.Credentials = new NetworkCredential(data.login, data.password); /* When in doubt, use these options */ ftpRequest.UseBinary = true; ftpRequest.UsePassive = true; ftpRequest.KeepAlive = true; /* Specify the Type of FTP Request */ ftpRequest.Method = WebRequestMethods.Ftp.MakeDirectory; /* Establish Return Communication with the FTP Server */ ftpResponse = (FtpWebResponse)ftpRequest.GetResponse(); /* Resource Cleanup */ ftpResponse.Close(); ftpRequest = null; }
/* 1st version of the method UploadFiles, used to upload one file. (KeepAlive = false) */ public static bool UploadFiles(string filePath, string networkPath, NetworkCredential credentials) { bool resultUpload = false; System.Threading.Thread.Sleep(500); Console.WriteLine("\nInitializing Network Connection.."); request = (FtpWebRequest)WebRequest.Create(UriPath(networkPath) + Path.GetFileName(filePath)); request.Method = WebRequestMethods.Ftp.UploadFile; request.UsePassive = true; request.KeepAlive = false; request.Credentials = credentials; /* set ssl protection? */ //request.EnableSsl = true; using (Stream requestStream = request.GetRequestStream()) { System.Threading.Thread.Sleep(500); Console.WriteLine("\nReading the file " + Path.GetFileName(filePath) + "..."); using (StreamReader sourceStream = new StreamReader(filePath)) { byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd()); sourceStream.Close(); request.ContentLength = fileContents.Length; requestStream.Write(fileContents, 0, fileContents.Length); requestStream.Close(); } } using (FtpWebResponse response = (FtpWebResponse)request.GetResponse()) { System.Threading.Thread.Sleep(500); Console.WriteLine("\nUpload of " + Path.GetFileName(filePath) + " file complete."); Console.WriteLine("Request status: {0}", response.StatusDescription); if (response.StatusDescription.Equals("226 Transfer complete.\r\n")) resultUpload = true; response.Close(); } Console.WriteLine("\nClosing connection to {0}...", string.Format("ftp://{0}", networkPath)); return resultUpload; }
private static void DownloadNewVersion() { request = (FtpWebRequest)WebRequest.Create(versionsInfo.ServerUrl + serverVersion.Version + ".zip"); request.Method = WebRequestMethods.Ftp.DownloadFile; request.Credentials = credentials; FtpWebResponse response = (FtpWebResponse)request.GetResponse(); Console.WriteLine("Downloading file to : " + versionsInfo.DownloadLocation + serverVersion.Version.ToString() + ".zip"); Stream responseStream = response.GetResponseStream(); using (var localFileStream = new FileStream(Path.Combine(versionsInfo.DownloadLocation, serverVersion.Version.ToString() + ".zip"), FileMode.Create)) { while ((bytesRead = responseStream.Read(buffer, 0, buffer.Length)) > 0) { totalBytesRead += bytesRead; localFileStream.Write(buffer, 0, bytesRead); } } }
/// <summary> /// 下載FTP檔案 /// 存儲至Client端桌面 /// </summary> /// <param name="FileName">要下載的檔案名稱</param> /// <returns></returns> public static bool Download(string FileName) { bool result = false; string LocalFile = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + "\\" + FileName; try { Uri FtpPath = new Uri(uriServer + FileName); ftpRequest = (FtpWebRequest)WebRequest.Create(FtpPath); ftpRequest.Credentials = new NetworkCredential(UserName,Password); ftpRequest.UseBinary = true; ftpRequest.UsePassive = true; ftpRequest.KeepAlive = true; ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile; ftpResponse = (FtpWebResponse)ftpRequest.GetResponse(); ftpStream = ftpResponse.GetResponseStream(); ftpFileStream = new FileStream(LocalFile, FileMode.Create); int BufferSize = 2048; byte[] byteBuffer = new byte[BufferSize]; int bytesRead = ftpStream.Read(byteBuffer, 0, BufferSize); try { while (bytesRead > 0) { ftpFileStream.Write(byteBuffer, 0, bytesRead); bytesRead = ftpStream.Read(byteBuffer, 0, BufferSize); } result = true; } catch (Exception ex) { sysMessage.SystemEx(ex.Message); } ftpFileStream.Close(); ftpStream.Close(); ftpResponse.Close(); ftpRequest = null; } catch (Exception ex) { sysMessage.SystemEx(ex.Message); } return result; }
/* Download File */ public void download(string remoteFile, string localFile) { try { /* Create an FTP Request */ ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host + "/" + remoteFile); /* Log in to the FTP Server with the User Name and Password Provided */ ftpRequest.Credentials = new NetworkCredential(user, pass); /* When in doubt, use these options */ ftpRequest.UseBinary = true; ftpRequest.UsePassive = true; ftpRequest.KeepAlive = true; /* Specify the Type of FTP Request */ ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile; /* Establish Return Communication with the FTP Server */ ftpResponse = (FtpWebResponse)ftpRequest.GetResponse(); /* Get the FTP Server's Response Stream */ ftpStream = ftpResponse.GetResponseStream(); /* Open a File Stream to Write the Downloaded File */ FileStream localFileStream = new FileStream(localFile, FileMode.Create); /* Buffer for the Downloaded Data */ byte[] byteBuffer = new byte[bufferSize]; int bytesRead = ftpStream.Read(byteBuffer, 0, bufferSize); /* Download the File by Writing the Buffered Data Until the Transfer is Complete */ try { while (bytesRead > 0) { localFileStream.Write(byteBuffer, 0, bytesRead); bytesRead = ftpStream.Read(byteBuffer, 0, bufferSize); } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } /* Resource Cleanup */ localFileStream.Close(); ftpStream.Close(); ftpResponse.Close(); ftpRequest = null; } catch (Exception ex) { Console.WriteLine(ex.ToString()); } return; }
/* Delete File */ public void Delete(string deleteFile) { try { ftpRequest = (FtpWebRequest)WebRequest.Create(host + "/" + deleteFile); ftpRequest.Credentials = new NetworkCredential(user, pass); ftpRequest.UseBinary = true; ftpRequest.UsePassive = true; ftpRequest.KeepAlive = true; ftpRequest.Method = WebRequestMethods.Ftp.DeleteFile; ftpResponse = (FtpWebResponse)ftpRequest.GetResponse(); ftpResponse.Close(); ftpRequest = null; } catch (Exception ex) { Console.WriteLine(ex.ToString()); } return; }
public override WorkerResult Run() { const int STATE_OK = 0; const int STATE_CRITICAL = 1; FtpWebRequest ftp = new FtpWebRequest(new Uri(DownloadFileUrl)); ftp.Credentials = new NetworkCredential(User, Password); ftp.Method = "GET"; FtpWebResponse response = ftp.GetResponse() as FtpWebResponse; if ( response.Status == 226 ) //226 = Transfer Complete { Stream responseStream = response.GetResponseStream(); FileStream fileStream = File.Open(LocalPath, FileMode.Create); byte [] buffer = new byte[32768]; if (responseStream.CanRead) { for (int bytesRead; (bytesRead = responseStream.Read(buffer, 0, buffer.Length)) > 0; ) fileStream.Write(buffer, 0, bytesRead); } responseStream.Close(); fileStream.Close(); return new WorkerResult(STATE_OK, WorkerResultStatus.Ok, string.Format(Description), string.Format(MessageOk, DateTime.Now) ); } else { Stream responseStream = response.GetResponseStream(); StreamReader responseReader = new StreamReader( responseStream ); string responseText = responseReader.ReadToEnd(); responseReader.Close(); responseStream.Close(); return new WorkerResult(STATE_CRITICAL, WorkerResultStatus.Critical, string.Format(Description), string.Format(MessageCritical, DateTime.Now, response.StatusDescription, responseText) ); } }
public void EliminarArchivo(string ArchivoEliminar) { try { Console.WriteLine("Iniciando proceso de eliminacion de archivo iniciado."); ftpRequest = (FtpWebRequest)FtpWebRequest.Create(Direccion + "/" + ArchivoEliminar); ftpRequest.Credentials = new NetworkCredential(Usuario, Password); ftpRequest.UseBinary = true; ftpRequest.UsePassive = true; ftpRequest.KeepAlive = true; ftpRequest.Method = WebRequestMethods.Ftp.DeleteFile; ftpResponse = (FtpWebResponse)ftpRequest.GetResponse(); Console.WriteLine("Archivo eliminado correctamente."); ftpResponse.Close(); ftpRequest = null; } catch (Exception) { Console.WriteLine("No se encuentra el archivo a eliminar"); } }
public bool test() { String uri = "ftp://" + host + "/"; req = (FtpWebRequest) FtpWebRequest.Create(new Uri(uri)); req.Credentials = new NetworkCredential(user, pass); req.KeepAlive = false; req.Method = WebRequestMethods.Ftp.ListDirectory; req.UseBinary = true; try { WebResponse response = req.GetResponse(); response.Close(); } catch (Exception) { return false; } return true; }
// Create Directory public void createRemoteDirectory(string newDirectory) { try { ftpRequest = (FtpWebRequest)WebRequest.Create(host + "/" + newDirectory); ftpRequest.Credentials = new NetworkCredential(user,pass); ftpRequest.UseBinary = true; ftpRequest.UsePassive = true; ftpRequest.KeepAlive = true; ftpRequest.Method = WebRequestMethods.Ftp.MakeDirectory; ftpResponse = (FtpWebResponse)ftpRequest.GetResponse(); ftpResponse.Close(); ftpRequest = null; } catch(Exception ex) { throw new Exception(ex.Message); } }
public void FtpUpload(string sourceFullPath) { FileInfo sourceFileInfo = new FileInfo(sourceFullPath); // set up ftp FtpRequest = (FtpWebRequest)FtpWebRequest.Create(String.Format(@"ftp://{0}/{1}/{2}", Url, RemoteDir, sourceFileInfo.Name)); FtpRequest.UsePassive = IsPassive; FtpRequest.KeepAlive = false; FtpRequest.Credentials = new NetworkCredential(FtpId, FtpPassword); FtpRequest.Method = WebRequestMethods.Ftp.UploadFile; byte[] fileContents = File.ReadAllBytes(sourceFullPath); FtpRequest.ContentLength = fileContents.Length; Stream requestStream = FtpRequest.GetRequestStream(); requestStream.Write(fileContents, 0, fileContents.Length); requestStream.Close(); FtpWebResponse response = (FtpWebResponse)FtpRequest.GetResponse(); response.Close(); }
public string DescargaArchivo(string ArchivoFTP, string ArchivoLocal) { try { ftpRequest = (FtpWebRequest)FtpWebRequest.Create(Direccion + "/" + ArchivoFTP); ftpRequest.Credentials = new NetworkCredential(Usuario, Password); ftpRequest.UseBinary = true; ftpRequest.UsePassive = true; ftpRequest.KeepAlive = true; Console.WriteLine("Iniciando proceso de Descarga de Archivo."); ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile; ftpResponse = (FtpWebResponse)ftpRequest.GetResponse(); ftpStream = ftpResponse.GetResponseStream(); FileStream ArchivoDescargado = new FileStream(ArchivoLocal, FileMode.Create); byte[] byteBuffer = new byte[2048]; int bytesRead = ftpStream.Read(byteBuffer, 0, 2048); while (bytesRead > 0) { ArchivoDescargado.Write(byteBuffer, 0, bytesRead); bytesRead = ftpStream.Read(byteBuffer, 0, 2048); } Console.WriteLine("Proceso de Descarga Finalizado."); EliminarArchivo(ArchivoFTP); ArchivoDescargado.Close(); ftpStream.Close(); ftpResponse.Close(); ftpRequest = null; return "Exito"; } catch (Exception) { Console.WriteLine("No se encuentra el archivo para descargar"); return "Error"; } }
// Delete File public void delete(string filePath) { try { ftpRequest = (FtpWebRequest)WebRequest.Create(host + "/" + filePath); ftpRequest.Credentials = new NetworkCredential(user, pass); ftpRequest.UseBinary = true; ftpRequest.UsePassive = true; ftpRequest.KeepAlive = true; ftpRequest.Method = WebRequestMethods.Ftp.DeleteFile; ftpResponse = (FtpWebResponse)ftpRequest.GetResponse(); ftpResponse.Close(); ftpRequest = null; } catch (Exception ex) { throw new Exception(ex.Message); } return; }
/* Delete File */ public void Delete(string deleteFile) { try { /* Create an FTP Request */ _ftpRequest = (FtpWebRequest)WebRequest.Create(_host + "/" + deleteFile); /* Log in to the FTP Server with the User Name and Password Provided */ _ftpRequest.Credentials = new NetworkCredential(_user, _pass); /* When in doubt, use these options */ _ftpRequest.UseBinary = true; _ftpRequest.UsePassive = true; _ftpRequest.KeepAlive = true; /* Specify the Type of FTP Request */ _ftpRequest.Method = WebRequestMethods.Ftp.DeleteFile; /* Establish Return Communication with the FTP Server */ _ftpResponse = (FtpWebResponse)_ftpRequest.GetResponse(); /* Resource Cleanup */ _ftpResponse.Close(); _ftpRequest = null; } catch (Exception ex) { Console.WriteLine(ex.ToString()); } return; }
public byte[] Download(string file, int chunksize = 2048) { MemoryStream outputStream; try { outputStream = new MemoryStream(); request = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + server + "/" + file)); request.Method = WebRequestMethods.Ftp.DownloadFile; request.UseBinary = true; request.Credentials = new NetworkCredential(username, password); FtpWebResponse response = (FtpWebResponse)request.GetResponse(); Stream ftpStream = response.GetResponseStream(); long cl = response.ContentLength; int bufferSize = 2048; int readCount; byte[] buffer = new byte[bufferSize]; readCount = ftpStream.Read(buffer, 0, bufferSize); while (readCount > 0) { outputStream.Write(buffer, 0, readCount); readCount = ftpStream.Read(buffer, 0, bufferSize); } ftpStream.Close(); outputStream.Close(); response.Close(); } catch (Exception ex) { Log.STR("Failed with message: \"" + ex.Message + "\""); return null; } return outputStream.ToArray(); }
public bool DownloadFileFTP(string destinfilepath, string ftphost, string ftpfilepath, string user, string pass) { try { ftpRequest = (FtpWebRequest)FtpWebRequest.Create("ftp://" + ftphost + "//" + ftpfilepath); ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile; ftpRequest.Credentials = new NetworkCredential(user, pass); ftpRequest.UseBinary = true; ftpRequest.UsePassive = true; ftpRequest.KeepAlive = true; ftpResponse = (FtpWebResponse)ftpRequest.GetResponse(); ftpStream = ftpResponse.GetResponseStream(); FileStream localFileStream = new FileStream(destinfilepath, FileMode.Create); byte[] byteBuffer = new byte[bufferSize]; int bytesRead = ftpStream.Read(byteBuffer, 0, bufferSize); while (bytesRead > 0) { localFileStream.Write(byteBuffer, 0, bytesRead); bytesRead = ftpStream.Read(byteBuffer, 0, bufferSize); } localFileStream.Close(); ftpStream.Close(); ftpResponse.Close(); ftpRequest = null; return true; } catch (Exception erro) { throw new Exception(erro.Message); } }
/// <summary> /// 连接FTP并执行命令 /// </summary> /// <param name="request"></param> /// <param name="url"></param> /// <param name="method"></param> /// <param name="user"></param> /// <param name="pass"></param> /// <returns></returns> private static FtpWebResponse Connect(ref FtpWebRequest request, string url, string method, string user, string pass) { request = (FtpWebRequest)FtpWebRequest.Create(url); request.UseBinary = true; request.Method = method; request.Credentials = new NetworkCredential(user, pass); return (FtpWebResponse)request.GetResponse(); }
/* List Directory Contents in Detail (Name, Size, Created, etc.) */ public string[] directoryListDetailed(string directory) { try { /* Create an FTP Request */ ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host + "/" + directory); /* Log in to the FTP Server with the User Name and Password Provided */ ftpRequest.Credentials = new NetworkCredential(user, pass); /* When in doubt, use these options */ ftpRequest.UseBinary = true; ftpRequest.UsePassive = true; ftpRequest.KeepAlive = true; /* Specify the Type of FTP Request */ ftpRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails; /* Establish Return Communication with the FTP Server */ ftpResponse = (FtpWebResponse)ftpRequest.GetResponse(); /* Establish Return Communication with the FTP Server */ ftpStream = ftpResponse.GetResponseStream(); /* Get the FTP Server's Response Stream */ StreamReader ftpReader = new StreamReader(ftpStream); /* Store the Raw Response */ string directoryRaw = null; /* Read Each Line of the Response and Append a Pipe to Each Line for Easy Parsing */ try { while (ftpReader.Peek() != -1) { directoryRaw += ftpReader.ReadLine() + "|"; } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } /* Resource Cleanup */ ftpReader.Close(); ftpStream.Close(); ftpResponse.Close(); ftpRequest = null; /* Return the Directory Listing as a string Array by Parsing 'directoryRaw' with the Delimiter you Append (I use | in This Example) */ try { string[] directoryList = directoryRaw.Split("|".ToCharArray()); return directoryList; } catch (Exception ex) { Console.WriteLine(ex.ToString()); } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } /* Return an Empty string Array if an Exception Occurs */ return new string[] { "" }; }
//查找ftp文件夹中的文件 public List<FtpFileInfo> GetFilesListByForder(string serverPath) { List<FtpFileInfo> lstfileName = new List<FtpFileInfo>(); StreamReader sr = null; //Uri uri = new Uri("ftp://" + ftpServer + "/" + serverPath); Uri uri = null; if (serverPath != "") uri = new Uri(serverPath); else uri = new Uri("ftp://" + ftpServer + "/"); try { ftpRequest = (FtpWebRequest)FtpWebRequest.Create(uri); if (ftpRequest == null) throw new Exception("无法打开ftp服务器连接"); ftpRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails; //列表 if (!IsAnonymous) { ftpRequest.Credentials = new NetworkCredential(userName, password); } sr = new StreamReader(ftpRequest.GetResponse().GetResponseStream()); while (!sr.EndOfStream)//读取列表 { char[] splitChar = { ' ' }; string temp = sr.ReadLine(); string[] tmpArray = temp.Split(splitChar, StringSplitOptions.RemoveEmptyEntries); if (tmpArray.Length != 9) { continue; } FtpFileInfo ffi = new FtpFileInfo(); ffi.IsDirectory = tmpArray[0].StartsWith("d"); string tempName= tmpArray[8].Replace(".",""); if(string.IsNullOrEmpty(tempName)) continue; ffi.FileName = tmpArray[8]; if (serverPath != "") ffi.FileFullName = serverPath + "/" + tmpArray[8]; else ffi.FileFullName = "ftp://" + ftpServer + "/" + tmpArray[8]; lstfileName.Add(ffi); } } catch (Exception ex) { //TODO: 异常处理. throw ex; } finally { if (sr != null) sr.Close(); } return lstfileName; }
//download method public void DownloadFile(string remoteFile, string localFile) { try { //Creating the FTP Request, its settings, and login handling// //sends request ftpRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(host + "/" + remoteFile)); //log in to the server with the credentials ftpRequest.Credentials = new NetworkCredential(username, password); //specifies request type ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile; //toggables// ftpRequest.UseBinary = true; //specifies file types for transfers is binary ftpRequest.UsePassive = true; //specifies that the connection is from the client to the server ftpRequest.KeepAlive = true; //specifies we want the connetion to continue after the request is complete //Creates the communication for the server to the client and creates a io stream in which the file can be written// //establishes server to client communication ftpResponse = (FtpWebResponse)ftpRequest.GetResponse(); //gets the servers response stream ftpStream = ftpResponse.GetResponseStream(); //creates a File Stream to write the downloaded file FileStream localFileStream = new FileStream(localFile + "\\" + remoteFile, FileMode.Create); //buffer for downloading the data in bytes it is an array of bytes of the size of the remote file. byte[] byteBuffer = new byte[Convert.ToInt32(getFileSize(remoteFile))]; //length of the bytes read in the stream int bytesRead = ftpStream.Read(byteBuffer, 0, Convert.ToInt32(getFileSize(remoteFile))); //bytes are read from the stream and the number of bytes read are stored into this variable //the stream reads in a maximum of bytes equal to the size of the remote file. these bytes are then stored into the bytebuffer array starting at the 0 position within the array. //the position of the stream is then advanced by the number of bytes in which are read try { while (bytesRead > 0) //loops until no bytes are being read { //writes the byte data into the local file localFileStream.Write(byteBuffer, 0, bytesRead); //reads more byte data bytesRead = ftpStream.Read(byteBuffer, 0, Convert.ToInt32(getFileSize(remoteFile))); } } catch (Exception ex) //error message { MessageBox.Show(ex.Message); } //closes processes and resources ftpResponse.Close(); ftpStream.Close(); localFileStream.Close(); ftpRequest = null; } catch (Exception ex) { MessageBox.Show(ex.Message); } }