/// <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); //} }
private DateTime GetFtpFileTime(string filename, string path, string hostName) { if (filename == "." || filename == "..") { return(DateTime.MaxValue); } try { string ftpurl = string.Format("ftp://{0}{1}{2}", hostName, path, filename); FtpWebRequest reqFTP = (System.Net.FtpWebRequest)System.Net.FtpWebRequest.Create(new Uri(ftpurl)); reqFTP.Method = System.Net.WebRequestMethods.Ftp.GetDateTimestamp; reqFTP.UseBinary = true; reqFTP.Credentials = new System.Net.NetworkCredential("anonymous", ""); System.Net.FtpWebResponse response = (System.Net.FtpWebResponse)reqFTP.GetResponse(); System.IO.Stream ftpStream = response.GetResponseStream(); string fileTime = response.LastModified.ToString(); ftpStream.Close(); response.Close(); return(Convert.ToDateTime(fileTime)); } catch { return(DateTime.MinValue); } }
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; }
/// <summary> /// Open Ftp file in a MemoryStream for read only. The FtpStream is copied in a MemoryStream. /// </summary> /// <param name="pStream">The ouput stream.</param> /// <param name="connectionGroupName">The group name for the connection</param> private void OpenReadFtpFile(out System.IO.Stream pStream, string connectionGroupName) { pStream = null; try { System.Net.FtpWebRequest lRequestFileDl = (System.Net.FtpWebRequest)System.Net.WebRequest.Create(_filePath); try { lRequestFileDl.ConnectionGroupName = connectionGroupName; lRequestFileDl.Method = System.Net.WebRequestMethods.Ftp.DownloadFile; System.Net.FtpWebResponse lResponseFileDl = (System.Net.FtpWebResponse)lRequestFileDl.GetResponse(); try { FileInfo lDestFileInfo = new FileInfo(_destRemoteFile); using (System.IO.FileStream lFileStream = lDestFileInfo.OpenWrite()) { using (System.IO.Stream lStream = lResponseFileDl.GetResponseStream()) { int i = 0; byte[] bytes = new byte[2048]; do { i = lStream.Read(bytes, 0, bytes.Length); lFileStream.Write(bytes, 0, i); } while (i != 0); lStream.Close(); } lFileStream.Close(); } pStream = lDestFileInfo.OpenRead(); pStream.Seek(0, System.IO.SeekOrigin.Begin); } finally { lResponseFileDl.Close(); } } finally { try { lRequestFileDl.Abort(); } catch (NotImplementedException) { // Ignore the not implemented exception } } } catch (Exception ex) { PIS.Ground.Core.LogMgmt.LogManager.WriteLog(TraceType.ERROR, ex.Message, "PIS.Ground.Core.Data.RemoteFileClass", ex, EventIdEnum.GroundCore); } }
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); } } }
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[] { }; }
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()); } } }
//二进制文件存储方法 protected void SaveBinaryFile(FtpWebResponse response) { byte[] buffer = new byte[1024]; string filename = convertFilename(response.ResponseUri); Stream outStream = File.Create(filename); Stream inStream = response.GetResponseStream(); int l; do { l = inStream.Read(buffer, 0, buffer.Length); if (l > 0) outStream.Write(buffer, 0, l); } while (l > 0); outStream.Close(); }
/// <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; }
public void DownloadFile() { try { _destinazione = Destinazione; if (!(Destinazione.StartsWith("ftp://") || Destinazione.StartsWith("ftp:\\\\"))) { _destinazione = "ftp://" + Destinazione; } System.Net.FtpWebRequest ftp = (System.Net.FtpWebRequest)System.Net.WebRequest.Create(new Uri(_destinazione + "/" + FileName)); ftp.Method = System.Net.WebRequestMethods.Ftp.DownloadFile; ftp.UseBinary = true; ftp.Credentials = new System.Net.NetworkCredential(UserFTP, PwdFTP); ftp = (System.Net.FtpWebRequest)System.Net.WebRequest.Create(new Uri(_destinazione + "/" + FileName)); ftp.Method = System.Net.WebRequestMethods.Ftp.DownloadFile; ftp.UseBinary = true; ftp.Credentials = new System.Net.NetworkCredential(UserFTP, PwdFTP); ftp.Method = System.Net.WebRequestMethods.Ftp.DownloadFile; System.Net.FtpWebResponse response = (System.Net.FtpWebResponse)ftp.GetResponse(); Stream responseStream = response.GetResponseStream(); StreamReader reader = new StreamReader(responseStream); using (StreamWriter writer = new StreamWriter(FilePath)) { writer.Write(reader.ReadToEnd()); } reader.Close(); response.Close(); } catch (Exception ex) { throw ex; } }
/* 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; }
// actually the only useful function in project. public DateTime GetFtpFileTime(string filename) { try { FtpWebRequest reqFTP = (System.Net.FtpWebRequest)System.Net.FtpWebRequest.Create(new Uri(filename)); reqFTP.Method = System.Net.WebRequestMethods.Ftp.GetDateTimestamp; reqFTP.UseBinary = true; reqFTP.Credentials = new System.Net.NetworkCredential(this.Username, this.Password); System.Net.FtpWebResponse response = (System.Net.FtpWebResponse)reqFTP.GetResponse(); System.IO.Stream ftpStream = response.GetResponseStream(); string fileTime = response.LastModified.ToString(); ftpStream.Close(); response.Close(); return(Convert.ToDateTime(fileTime)); } catch/* (Exception ex)*/ { return(DateTime.MinValue); } }
public List <string> GetListOfExistingFilesNames() { System.Net.FtpWebRequest ftpRequest = (System.Net.FtpWebRequest)System.Net.WebRequest.Create(ftpServerPath); ftpRequest.Credentials = new System.Net.NetworkCredential(userId, password); ftpRequest.Method = WebRequestMethods.Ftp.ListDirectory; System.Net.FtpWebResponse response = (System.Net.FtpWebResponse)ftpRequest.GetResponse(); System.IO.StreamReader streamReader = new System.IO.StreamReader(response.GetResponseStream()); List <string> directories = new List <string>(); string line = streamReader.ReadLine(); while (!string.IsNullOrEmpty(line)) { directories.Add(line); line = streamReader.ReadLine(); } streamReader.Close(); return(directories); }
//Sorts the files and only shows the files you want. public List<String> listFiles(FtpWebResponse files, Boolean showAllFiles) { Stream responseStream = files.GetResponseStream(); StreamReader reader = new StreamReader(responseStream); String filesFolders = reader.ReadToEnd(); List<String> fileArray = filesFolders.Split('\n').ToList<String>(); List<String> newList = new List<string>(); if (!showAllFiles) { foreach (String s in fileArray) { if (s.Contains(".mp3") || s.StartsWith("d")) //Feel free to add the filetypes you like. { if (s.Length > 0) { Char[] c = s.ToCharArray(); for (int i = 0; i < c.Length; i++) { if (c[i] == ':') { newList.Add(s.Substring(i + 4)); } } } } } } else { foreach (String s in fileArray) { newList.Add(s); //Adds all directorydetails } } newList.Sort(); return newList; }
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"; } }
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); } }
//gets files in a directory and outputs them as a string public string[] lsDirectory(string dir) { string[] filesInDir = new string[10]; try { ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host + "/" + dir); ftpRequest.Credentials = new NetworkCredential(username, password); ftpRequest.UsePassive = true; ftpRequest.UseBinary = true; ftpRequest.KeepAlive = true; ftpRequest.Method = WebRequestMethods.Ftp.ListDirectory; ftpResponse = (FtpWebResponse)ftpRequest.GetResponse(); ftpStream = ftpResponse.GetResponseStream(); StreamReader sr = new StreamReader(ftpStream); //since this is only for input string dirRaw = null; //used to store the raw response try { while (sr.Peek() != -1) //until no more avaliable characters { dirRaw += sr.ReadLine() + "|"; //adds on lines to our raw directory variable with "|" seperating lines for easier parsing } } catch (Exception ex) { MessageBox.Show(ex.Message); } //close resources ftpResponse.Close(); sr.Close(); ftpStream.Close(); ftpRequest = null; try { filesInDir = dirRaw.Split("|".ToCharArray()); //gets rid of | return filesInDir; } catch (Exception ex) { MessageBox.Show(ex.Message); } } catch (Exception ex) { MessageBox.Show(ex.Message); } return filesInDir; }
public string File_List_Remote_Computer() { try { // I set the Ip address of the remote computer string IpAddress = ""; IpAddress = this.host; // I set the credentials of the remote computer. string UserName = this.user; string UserPassword = this.password; // I set the Ftp object. System.Net.FtpWebRequest FtpWebRequest = (System.Net.FtpWebRequest)System.Net.WebRequest.Create(IpAddress); FtpWebRequest.Credentials = new System.Net.NetworkCredential(UserName, UserPassword); FtpWebRequest.Method = System.Net.WebRequestMethods.Ftp.ListDirectory; FtpWebRequest.Proxy = null; System.Net.FtpWebResponse FtpWebResponse = (System.Net.FtpWebResponse)FtpWebRequest.GetResponse(); // I set the StreamReader object. // It will contain the file list of the remote computer System.IO.StreamReader StreamReader = new System.IO.StreamReader (FtpWebResponse.GetResponseStream(), System.Text.Encoding.ASCII); // I set the DataFound variable. bool DataFound = false; // I set FileName variable. string FileName = ""; // I loop on the StreamReader object. while (StreamReader.EndOfStream == false) { System.IO.FileStream sr = new System.IO.FileStream(host + "/" + FileName, System.IO.FileMode.Open); DataFound = true; FileName = StreamReader.ReadLine().ToString(); return(FileName + "|" + sr.Length); } // If the value of the DataFound variable is // False then no data was found. if (DataFound == false) { return("No data found."); } // I close the objects. StreamReader.Close(); FtpWebResponse.Close(); FtpWebRequest = null; return(""); } catch (Exception ex) { // I show an error message if the sub generates an error. if (ex.Message.Contains("(530)")) { return("User name or password is wrong."); } else { return("Error message: " + ex.Message); } } }
/* 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[] { "" }; }
private string[] lsSimple(string dir) { try { ftpRequest = (FtpWebRequest)WebRequest.Create(String.Format(baseUrl, dir)); ftpRequest.Credentials = new NetworkCredential(userName, password); ftpRequest.UseBinary = true; ftpRequest.UsePassive = true; ftpRequest.KeepAlive = true; ftpRequest.EnableSsl = true; ftpRequest.Method = WebRequestMethods.Ftp.ListDirectory; ftpResponse = (FtpWebResponse)ftpRequest.GetResponse(); ftpStream = ftpResponse.GetResponseStream(); StreamReader ftpReader = new StreamReader(ftpStream); StringBuilder result = new StringBuilder(); try { string line = ftpReader.ReadLine(); while (line != null) { result.Append(line); result.Append("\n"); line = ftpReader.ReadLine(); } //remove extra \n result.Remove(result.ToString().LastIndexOf('\n'), 1); ftpReader.Close(); ftpStream.Close(); ftpResponse.Close(); ftpRequest = null; return result.ToString().Split('\n'); } catch (Exception ex) { Console.WriteLine("Error reading file list.\n" + ex.ToString()); if (result != null) result = null; if (ftpReader != null) ftpReader.Close(); if (ftpResponse != null) ftpResponse.Close(); if (ftpRequest != null) ftpRequest = null; return new string[] { "" }; } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } return new string[] { "" }; }
// Anslutning till FTP - Server och listar innehållet public bool LoginCheck() { try { // Skapa en FTP Request */ ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host+":"+port); // Loggar in på FTP Server med användarnman och lösenord ftpRequest.Credentials = new NetworkCredential(user, pass); ftpRequest.UseBinary = true; ftpRequest.UsePassive = true; ftpRequest.KeepAlive = true; //Specificerar vilken typ av FTP Request ftpRequest.Method = WebRequestMethods.Ftp.ListDirectory; //Etablera Return kommunikation med FTP-servern ftpResponse = (FtpWebResponse)ftpRequest.GetResponse(); // Lagra FTP Serverns svarström ftpStream = ftpResponse.GetResponseStream(); // Lagra FTP Serverns svarström StreamReader ftpReader = new StreamReader(ftpStream); // Lagrar responesen i variabeln directoryRaw string directoryRaw = null; // Läser rad för ar av svaret och lägger till en | för varje rad try { while (ftpReader.Peek() != -1) { directoryRaw += ftpReader.ReadLine() + "|"; } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } // Städar anslutningarna ftpReader.Close(); ftpStream.Close(); ftpResponse.Close(); ftpRequest = null; try { string[] directoryList = directoryRaw.Split("|".ToCharArray()); Console.WriteLine(""); Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("========================================"); Console.ResetColor(); Console.WriteLine("Content of the FTP-Server"); Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("========================================"); Console.ResetColor(); foreach (var direct in directoryList) { Console.WriteLine(direct); } Console.WriteLine(""); Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("========================================"); Console.ResetColor(); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } } catch (Exception) { return false; } return true; }
//метод протокола FTP RETR для загрузки файла с FTP-сервера public void DownloadFile(string path, string fileName) { ftpRequest = (FtpWebRequest)WebRequest.Create("ftp://" + _Host + path + "/" + fileName); ftpRequest.Credentials = new NetworkCredential(_UserName, _Password); //команда фтп RETR ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile; ftpRequest.EnableSsl = _UseSSL; //Файлы будут копироваться в кталог программы FileStream downloadedFile = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite); ftpResponse = (FtpWebResponse)ftpRequest.GetResponse(); //Получаем входящий поток Stream responseStream = ftpResponse.GetResponseStream(); //Буфер для считываемых данных byte[] buffer = new byte[1024]; int size = 0; while ((size = responseStream.Read(buffer, 0, 1024)) > 0) { downloadedFile.Write(buffer, 0, size); } ftpResponse.Close(); downloadedFile.Close(); responseStream.Close(); }
public void download(string remoteFile, string localFile) { FileStream localFileStream = null; try { ftpRequest = (FtpWebRequest)WebRequest.Create(String.Format(baseUrl, remoteFile)); ftpRequest.Credentials = new NetworkCredential(userName, password); ftpRequest.UseBinary = false; //TODO: figure out why this downloads correctly when in most cases with windows it shouldn't ftpRequest.UsePassive = true; ftpRequest.KeepAlive = true; ftpRequest.EnableSsl = true; ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile; ftpResponse = (FtpWebResponse)ftpRequest.GetResponse(); ftpStream = ftpResponse.GetResponseStream(); localFileStream = new FileStream(localFile, FileMode.Create); byte[] buffer = new byte[bufferSize]; int bytesRead = ftpStream.Read(buffer, 0, bufferSize); try { while (bytesRead > 0) { localFileStream.Write(buffer, 0, bufferSize); bytesRead = ftpStream.Read(buffer, 0, bufferSize); } } catch (Exception ex) { if (localFileStream != null) localFileStream.Close(); Console.WriteLine("Error reading remote file.\n" + ex.ToString()); } localFileStream.Close(); ftpStream.Close(); ftpResponse.Close(); ftpRequest = null; } catch(Exception ex) { if (ftpRequest != null) ftpRequest = null; if (localFileStream != null) localFileStream.Close(); if (ftpResponse != null) ftpResponse.Close(); if (ftpStream != null) ftpStream.Close(); Console.WriteLine("Error downloading file.\n" + ex.ToString()); } }
private void logThreadWork() { while (true) { if (stream == null || !stream.CanRead) { ftpRequest = (FtpWebRequest)FtpWebRequest.Create(data.adress + "/logs/latest.log"); ftpRequest.Credentials = new NetworkCredential(data.login, data.password); ftpRequest.UseBinary = true; ftpRequest.UsePassive = true; ftpRequest.KeepAlive = true; ftpRequest.ContentOffset = logLength; ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile; ftpResponse = (FtpWebResponse)ftpRequest.GetResponse(); stream = ftpResponse.GetResponseStream(); } byte[] buffer = new byte[2048]; bytesRead = 2048; while (bytesRead == 2048) { bytesRead = stream.Read(buffer, 0, 2048); logLength += bytesRead; if (bytesRead > 0) { try { text.Invoke(new Action(() => { text.AppendText(Encoding.UTF8.GetString(buffer, 0, bytesRead)); text.Navigate(text.Lines.Count - 1); })); } catch (Exception) { } } } } }
/// <summary> /// 下载FTP文件 /// </summary> /// <param name="part"></param> void DownloadFTPFile(string key, FTPItem part, double filesize) { try { //下载文件的URI Uri u = new Uri(part.ServerFilePath); //设定下载文件的保存路径 string downFile = part.LocFilePath; //FtpWebRequest的作成 System.Net.FtpWebRequest ftpReq = (System.Net.FtpWebRequest)System.Net.WebRequest.Create(u); //设定用户名和密码 ftpReq.Credentials = new System.Net.NetworkCredential(FTPUser, FTPPassword); //MethodにWebRequestMethods.Ftp.DownloadFile("RETR")设定 ftpReq.Method = System.Net.WebRequestMethods.Ftp.DownloadFile; //要求终了后关闭连接 ftpReq.KeepAlive = false; //使用ASCII方式传送 ftpReq.UseBinary = false; //设定PASSIVE方式无效 ftpReq.UsePassive = false; //判断是否继续下载 //继续写入下载文件的FileStream System.IO.FileStream fs; if (part.IsContinue) { if (System.IO.File.Exists(downFile)) { //继续下载 ftpReq.ContentOffset = (new System.IO.FileInfo(downFile)).Length; fs = new System.IO.FileStream(downFile, System.IO.FileMode.Append, System.IO.FileAccess.Write); } else { //一般下载 fs = new System.IO.FileStream(downFile, System.IO.FileMode.Create, System.IO.FileAccess.Write); } } else { if (System.IO.File.Exists(downFile)) { File.Delete(downFile); } //一般下载 fs = new System.IO.FileStream(downFile, System.IO.FileMode.Create, System.IO.FileAccess.Write); } //取得FtpWebResponse System.Net.FtpWebResponse ftpRes = (System.Net.FtpWebResponse)ftpReq.GetResponse(); //为了下载文件取得Stream System.IO.Stream resStrm = ftpRes.GetResponseStream(); //写入下载的数据 byte[] buffer = new byte[20480]; double posLen = 0; while (part.CloseState == false && part.RunState == FTPRunState.Run) { int readSize = resStrm.Read(buffer, 0, buffer.Length); posLen += readSize; if (readSize == 0) { break; } fs.Write(buffer, 0, readSize); if (OnProgressChanged != null) { //System.Threading.Tasks.Task.Factory.StartNew(() => //{ OnProgressChanged(key, Math.Round((posLen / filesize) * 100, 2)); //}); } } fs.Close(); resStrm.Close(); if (part.RunState == FTPRunState.Run) { UploadFileList.TryRemove(key, out part); if (OnProgressChanged != null) { OnProgressChanged(key, 100.00); } if (OnCompleted != null) { OnCompleted(key, part.ServerFilePath); } } //表示从FTP服务器被送信的状态 //Console.WriteLine("{0}: {1}", ftpRes.StatusCode, ftpRes.StatusDescription); //关闭连接 ftpRes.Close(); } catch (Exception ex) { part.RunState = FTPRunState.Error; UploadFileList.TryRemove(key, out part);//出错则删除 OnFailed(key, 150); } }
/*************************************************\ * List Directory Contents File/Folder Name Only * \*************************************************/ public void GetDirectoryList(Directory directory, BackgroundWorker worker, DoWorkEventArgs e) { /* Set parameters and return values */ List<object> parameters = e.Argument as List<object>; List<object> returnArguments = new List<object>(); if (((string)parameters[0]).Equals("GetDir")) { if (directory.Get_IsRoot()) returnArguments.Add("GetDir"); } else if (((string)parameters[0]).Equals("DlLastUp")) { returnArguments.Add("DlLastUp"); } else if (((string)parameters[0]).Equals("SyncLF")) { returnArguments.Add("SyncLF"); } else if (((string)parameters[0]).Equals("ChDir")) { returnArguments.Add("ChDir"); } if (directory.Get_FoldersList().Count == 0 && directory.Get_FilesList().Count == 0) { try { // FYI // http://stackoverflow.com/questions/1016690/how-to-improve-the-performance-of-ftpwebrequest /* Instanciate FTP request */ worker.ReportProgress(0); _FtpRequest = (FtpWebRequest)FtpWebRequest.Create(_Host); /* Log in */ _FtpRequest.Credentials = new NetworkCredential(_User, _Password); /* Set options */ _FtpRequest.UseBinary = true; _FtpRequest.UsePassive = true; _FtpRequest.KeepAlive = true; _FtpRequest.ConnectionGroupName = "GetDirectoryList"; // To ensure that the connection pool is used _FtpRequest.KeepAlive = true; _FtpRequest.ServicePoint.ConnectionLimit = 2; /* Specify type of request */ _FtpRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails; worker.ReportProgress(30); /* Establish return communication with ftp server */ _FtpResponse = (FtpWebResponse)_FtpRequest.GetResponse(); worker.ReportProgress(60); /* Establish return communication with ftp server */ //_FtpStream = _FtpResponse.GetResponseStream(); using (Stream ftpStream = _FtpResponse.GetResponseStream()) { if (worker.CancellationPending) { e.Cancel = true; } else { /* get FTP server's response stream */ StreamReader ftpReader = new StreamReader(ftpStream, Encoding.ASCII); /* Read Each Line of the Response and Append a Pipe to Each Line for Easy Parsing */ List<string> lines = new List<string>(); // temporary list string htmlResult = String.Empty; string line = ftpReader.ReadLine(); while (line != null && line != String.Empty) { if (worker.CancellationPending) { e.Cancel = true; break; } lines.Add(line); htmlResult += line; line = ftpReader.ReadLine(); } worker.ReportProgress(80); /* parse HTML output (first, get only the name of file, then re-parse to get the timestamp/size */ try { //List<string> content = new List<string>(); HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument(); doc.LoadHtml(htmlResult); foreach (HtmlAgilityPack.HtmlNode node in doc.DocumentNode.SelectNodes("//a[@href]")) { if (worker.CancellationPending) { e.Cancel = true; break; } else if (!node.InnerText.Contains(">") && !String.IsNullOrEmpty(node.InnerText)) { /* suppress last char '/' */ string stringRaw = node.InnerText; if (stringRaw[stringRaw.Length - 1] == '/') stringRaw = stringRaw.Substring(0, stringRaw.Length - 1); string[] split = stringRaw.Split('/'); /* Parse timestamp and size, and then fill directory object */ ParseSizeAndTimestamp(directory, split[split.Length - 1], lines); } else if (node.InnerText.Contains(">") && !String.IsNullOrEmpty(node.InnerText)) { /* suppress last char '/' */ string stringRaw = node.Attributes[0].Value; if (stringRaw[stringRaw.Length - 1] == '/') stringRaw = stringRaw.Substring(0, stringRaw.Length - 1); string[] split = stringRaw.Split('/'); /* Parse timestamp and size, and then fill directory object */ ParseSizeAndTimestamp(directory, split[split.Length - 1], lines); } } } catch (Exception ex) { returnArguments.Add(ex.ToString()); } /* Resource Cleanup */ ftpReader.Close(); _FtpResponse.Close(); _FtpRequest = null; } } } catch (Exception ex) { returnArguments.Add(ex.ToString()); } } worker.ReportProgress(100); e.Result = returnArguments; }
private bool Download(string sourcePath, string destinationPath, int offsetByte = 0) { var ftpWebRequest = GetFtpWebRequest(sourcePath); ftpWebRequest.Method = WebRequestMethods.Ftp.DownloadFile; ftpWebRequest.ContentOffset = offsetByte; LogStepFtpRequest(ftpWebRequest.RequestUri, string.Format("{0} {1}, {2}", ftpWebRequest.Method, sourcePath, destinationPath)); var result = false; var fileInfo = new FileInfo(destinationPath); using (var fileStream = fileInfo.OpenWrite()) { try { LastResponse = (FtpWebResponse) ftpWebRequest.GetResponse(); var responseStream = LastResponse.GetResponseStream(); fileStream.Seek(offsetByte, SeekOrigin.Begin); result = TransferData(responseStream, fileStream); } catch (WebException ex) { TestEasyLog.Instance.Failure(string.Format("Exception while getting FTP response: '{0}'", ex.Message)); LastResponse = (FtpWebResponse) ex.Response; } catch (InvalidOperationException ex2) { TestEasyLog.Instance.Failure(string.Format("Exception while getting FTP response: '{0}'", ex2.Message)); } finally { if (LastResponse != null) { LastResponse.Close(); } } } return result; }
/// <summary> /// 从FTP服务器下载文件,返回文件二进制数据 /// </summary> /// <param name="RemoteFileName">远程文件名</param> public byte[] DownloadFile(string RemoteFileName) { try { if (!IsValidFileChars(RemoteFileName)) { throw new Exception("非法文件名或目录名!"); } Response = Open(new Uri(this.Uri.ToString() + RemoteFileName), WebRequestMethods.Ftp.DownloadFile); Stream Reader = Response.GetResponseStream(); MemoryStream mem = new MemoryStream(1024 * 500); byte[] buffer = new byte[1024]; int bytesRead = 0; int TotalByteRead = 0; while (true) { bytesRead = Reader.Read(buffer, 0, buffer.Length); TotalByteRead += bytesRead; if (bytesRead == 0) break; mem.Write(buffer, 0, bytesRead); } if (mem.Length > 0) { return mem.ToArray(); } else { return null; } } catch (Exception ep) { ErrorMsg = ep.ToString(); throw ep; } }
/// <summary> /// 列出FTP服务器上面当前目录的所有文件和目录 /// </summary> public FileStruct[] ListFilesAndDirectories() { Response = Open(this.Uri, WebRequestMethods.Ftp.ListDirectoryDetails); StreamReader stream = new StreamReader(Response.GetResponseStream(), Encoding.Default); string Datastring = stream.ReadToEnd(); FileStruct[] list = GetList(Datastring); return list; }
public void Exec(Int32 ImageSend) { try { Model.Local.ArticleImageRepository ArticleImageRepository = new Model.Local.ArticleImageRepository(); if (ArticleImageRepository.ExistPre_Id(ImageSend) == false) { Model.Prestashop.PsImageRepository PsImageRepository = new Model.Prestashop.PsImageRepository(); Model.Prestashop.PsImage PsImage = PsImageRepository.ReadImage(Convert.ToUInt32(ImageSend)); Model.Local.ArticleRepository ArticleRepository = new Model.Local.ArticleRepository(); if (ArticleRepository.ExistPre_Id(Convert.ToInt32(PsImage.IDProduct))) { Model.Local.Article Article = ArticleRepository.ReadPre_Id(Convert.ToInt32(PsImage.IDProduct)); Model.Prestashop.PsImageLangRepository PsImageLangRepository = new Model.Prestashop.PsImageLangRepository(); if (PsImageLangRepository.ExistImageLang(Convert.ToUInt32(ImageSend), Core.Global.Lang)) { string extension = Core.Img.jpgExtension; String FTP = Core.Global.GetConfig().ConfigFTPIP; String User = Core.Global.GetConfig().ConfigFTPUser; String Password = Core.Global.GetConfig().ConfigFTPPassword; Model.Prestashop.PsImageLang PsImageLang = PsImageLangRepository.ReadImageLang(Convert.ToUInt32(ImageSend), Core.Global.Lang); Model.Local.ArticleImage ArticleImage = new Model.Local.ArticleImage() { ImaArt_Name = (!String.IsNullOrEmpty(PsImageLang.Legend)) ? PsImageLang.Legend : Article.Art_Ref, ImaArt_Position = PsImage.Position, ImaArt_Default = Convert.ToBoolean(PsImage.Cover), Pre_Id = Convert.ToInt32(PsImage.IDImage), Art_Id = Article.Art_Id, ImaArt_Image = string.Empty, ImaArt_SourceFile = SearchFreeNameFile(Article.Art_Id, Article.Art_Ref, extension), ImaArt_DateAdd = DateTime.Now }; ArticleImageRepository.Add(ArticleImage); Boolean import_img = false; try { // <JG> 10/04/2013 gestion système d'images string ftpPath = "/img/p/"; switch (Core.Global.GetConfig().ConfigImageStorageMode) { case Core.Parametres.ImageStorageMode.old_system: #region old_system // no action on path break; #endregion case Core.Parametres.ImageStorageMode.new_system: default: #region new_system foreach (char directory in PsImage.IDImage.ToString()) { ftpPath += directory + "/"; } break; #endregion } // <JG> 21/05/2013 import image originale Boolean import_img_tmp = false; try { string ftpfullpath = (Core.Global.GetConfig().ConfigImageStorageMode == Core.Parametres.ImageStorageMode.old_system) ? FTP + ftpPath + PsImage.IDProduct + "-" + PsImage.IDImage + Core.Img.jpgExtension : FTP + ftpPath + PsImage.IDImage + Core.Img.jpgExtension; bool existfile = Core.Ftp.ExistFile(ftpfullpath, User, Password); if (existfile) { System.Net.FtpWebRequest ftp = (System.Net.FtpWebRequest)System.Net.FtpWebRequest.Create(ftpfullpath); ftp.Credentials = new System.Net.NetworkCredential(User, Password); ftp.UseBinary = true; ftp.UsePassive = true; ftp.KeepAlive = false; ftp.EnableSsl = Core.Global.GetConfig().ConfigFTPSSL; System.Net.FtpWebResponse response = (System.Net.FtpWebResponse)ftp.GetResponse(); Stream reader = response.GetResponseStream(); MemoryStream memStream = new MemoryStream(); byte[] buffer = new byte[1024]; byte[] downloadedData = new byte[0]; while (true) { int bytesRead = reader.Read(buffer, 0, buffer.Length); if (bytesRead != 0) { memStream.Write(buffer, 0, bytesRead); } else { break; } downloadedData = memStream.ToArray(); } string target_folder = (Core.Global.GetConfig().ConfigLocalStorageMode == Parametres.LocalStorageMode.simple_system) ? Global.GetConfig().Folders.TempArticle : ArticleImage.advanced_folder; if (downloadedData != null && downloadedData.Length != 0) { FileStream newFile = new FileStream( System.IO.Path.Combine(target_folder, String.Format("{0}" + extension, ArticleImage.ImaArt_Id)), FileMode.Create); newFile.Write(downloadedData, 0, downloadedData.Length); newFile.Close(); newFile.Dispose(); memStream.Dispose(); downloadedData = new byte[0]; } string local_file_tmp = System.IO.Path.Combine(target_folder, String.Format("{0}" + extension, ArticleImage.ImaArt_Id)); // <JG> 30/09/2013 détection encodage PNG lors de l'import Boolean rename_to_png = false; System.Drawing.Image img = System.Drawing.Image.FromFile(local_file_tmp); var imgguid = img.RawFormat.Guid; img.Dispose(); System.Drawing.Imaging.ImageCodecInfo search; foreach (System.Drawing.Imaging.ImageCodecInfo codec in System.Drawing.Imaging.ImageCodecInfo.GetImageDecoders()) { if (codec.FormatID == imgguid) { search = codec; if (search.FormatDescription == "PNG") { rename_to_png = true; } break; } } if (rename_to_png) { if (System.IO.File.Exists(local_file_tmp)) { extension = Core.Img.pngExtension; System.IO.File.Move(local_file_tmp, System.IO.Path.Combine(target_folder, String.Format("{0}" + extension, ArticleImage.ImaArt_Id))); } ArticleImage.ImaArt_SourceFile = SearchFreeNameFile(Article.Art_Id, Article.Art_Ref, extension); } ArticleImage.ImaArt_Image = String.Format("{0}" + extension, ArticleImage.ImaArt_Id); ArticleImageRepository.Save(); Core.Img.resizeImage(new System.Drawing.Bitmap(ArticleImage.TempFileName), Core.Global.GetConfig().ConfigImageMiniatureWidth, Core.Global.GetConfig().ConfigImageMiniatureHeight, ArticleImage.SmallFileName); import_img_tmp = true; } } catch (Exception) { // Not implemented } if (import_img_tmp) { Model.Prestashop.PsImageTypeRepository PsImageTypeRepository = new Model.Prestashop.PsImageTypeRepository(); List <Model.Prestashop.PsImageType> ListPsImageType = PsImageTypeRepository.ListProduct(1); foreach (Model.Prestashop.PsImageType PsImageType in ListPsImageType) { string ftpfullpath = (Core.Global.GetConfig().ConfigImageStorageMode == Core.Parametres.ImageStorageMode.old_system) ? FTP + ftpPath + PsImage.IDProduct + "-" + PsImage.IDImage + "-" + PsImageType.Name + Core.Img.jpgExtension : FTP + ftpPath + PsImage.IDImage + "-" + PsImageType.Name + Core.Img.jpgExtension; System.Net.FtpWebRequest ftp = (System.Net.FtpWebRequest)System.Net.FtpWebRequest.Create(ftpfullpath); ftp.Credentials = new System.Net.NetworkCredential(User, Password); ftp.UseBinary = true; ftp.UsePassive = true; ftp.KeepAlive = false; ftp.EnableSsl = Core.Global.GetConfig().ConfigFTPSSL; System.Net.FtpWebResponse response = (System.Net.FtpWebResponse)ftp.GetResponse(); Stream reader = response.GetResponseStream(); MemoryStream memStream = new MemoryStream(); byte[] buffer = new byte[1024]; byte[] downloadedData = new byte[0]; while (true) { int bytesRead = reader.Read(buffer, 0, buffer.Length); if (bytesRead != 0) { memStream.Write(buffer, 0, bytesRead); } else { break; } downloadedData = memStream.ToArray(); } if (downloadedData != null && downloadedData.Length != 0) { FileStream newFile = new FileStream(ArticleImage.FileName(PsImageType.Name), FileMode.Create); newFile.Write(downloadedData, 0, downloadedData.Length); newFile.Close(); } } import_img = true; // gestion image par défaut if (ArticleImage.ImaArt_Default) { List <Model.Local.ArticleImage> ListArticleImage = ArticleImageRepository.ListArticle(ArticleImage.Art_Id.Value); if (ListArticleImage.Count(i => i.ImaArt_Default == true && i.ImaArt_Id != ArticleImage.ImaArt_Id) > 0) { foreach (Model.Local.ArticleImage ArticleImageDefault in ListArticleImage.Where(i => i.ImaArt_Default == true && i.ImaArt_Id != ArticleImage.ImaArt_Id)) { ArticleImageDefault.ImaArt_Default = false; ArticleImageRepository.Save(); } } } // liens images déclinaisons ExecAttributeImage(PsImage, ArticleImage); } } catch (Exception ex) { Core.Error.SendMailError("[DOWNLOAD FTP IMAGE ARTICLE]<br />" + ex.ToString()); ArticleImageRepository.Delete(ArticleImage); } if (!import_img) { ArticleImageRepository.Delete(ArticleImage); } } } } else if (ArticleImageRepository.ExistPrestaShop(ImageSend)) { // import des affectations aux déclinaisons Model.Prestashop.PsImageRepository PsImageRepository = new Model.Prestashop.PsImageRepository(); Model.Prestashop.PsImage PsImage = PsImageRepository.ReadImage(Convert.ToUInt32(ImageSend)); Model.Local.ArticleImage ArticleImage = ArticleImageRepository.ReadPrestaShop(ImageSend); ExecAttributeImage(PsImage, ArticleImage); } } catch (Exception ex) { Core.Error.SendMailError(ex.ToString()); } }
public void VerificarArquivos(string sPathDestino, string ftphost, string ftpfilepath, string user, string pass) { try { ftpRequest = (FtpWebRequest)FtpWebRequest.Create("ftp://" + ftphost + "//" + ftpfilepath); ftpRequest.Method = WebRequestMethods.Ftp.ListDirectory; ftpRequest.Credentials = new NetworkCredential(user, pass); ftpRequest.UseBinary = true; ftpRequest.UsePassive = true; ftpRequest.KeepAlive = true; ftpResponse = (FtpWebResponse)ftpRequest.GetResponse(); StreamReader sr = new StreamReader(ftpResponse.GetResponseStream()); string str = sr.ReadLine(); while (str != null) { Console.WriteLine(str); str = sr.ReadLine(); if (str != ".." && str!=null) { if (!DownloadFileFTP((sPathDestino + "\\" + str), ftphost, (ftpfilepath.Replace("\\", "//") + "//" + str), user, pass)) { return; } else { conn.ExecutarComando("INSERT INTO LOG_ARQUIVOS_RECEBIDOS (CODVEN, ARQUIVO, NOME_ARQUIVO) VALUES (" + str.Substring(0, 2) + ", '" + (sPathDestino + "\\" + str) + "', '" + str + "')"); //Excluir arquivo já recebido do FTP DeleteFileFTP(ftphost, (ftpfilepath.Replace("\\", "//") + "//" + str), user, pass); } } } ftpResponse.Close(); ftpRequest = null; } catch (Exception exc) { this.sErro = exc.Message; } }
/// <summary> /// amocmebs CSV fails, aris tu ara axali gadacemis chanaceri /// </summary> /// <returns>abrunebs true-s tu axali gadacema daicko, tuarada false-s.</returns> public static bool nextCSVResult(out string sShemdegiGadacemisSaxeli , out DateTime dtAxaliGadacemisDackebisDro) { //string[] lsAllLines = File.ReadAllLines(File.ReadAllText(VideoCaptureController.sFileContainingInfoAboutCSVFilePath)); FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create("ftp://92.241.90.13/" + "OAStudioLog" + DateTime.Now.Year.ToString() + RecorderController.add_zeros(DateTime.Now.Month.ToString()) + RecorderController.add_zeros(DateTime.Now.Day.ToString()) + ".csv"); ftp.Credentials = new NetworkCredential("log", "log"); ftp.CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore);//nocachenostore? try { System.Net.FtpWebResponse resp = (FtpWebResponse)ftp.GetResponse(); StreamReader csv = new StreamReader(resp.GetResponseStream(), Encoding.ASCII); // string[] lsAllLines = csv.ReadToEnd().Replace("\r", "").Split('\n'); // int lastValidLineNum = lsAllLines.Length - 1; while ("" == lsAllLines[lastValidLineNum] || lsAllLines[lastValidLineNum].Split(',').Length < 7 || "On Air Studio terminated" == lsAllLines[lastValidLineNum].Split(',')[6] || (lsAllLines[lastValidLineNum].Split(',').Length > 7 && "Playback Stopped" == lsAllLines[lastValidLineNum].Split(',')[7]) || !(lsAllLines[lastValidLineNum].LastIndexOf(',') > lsAllLines[lastValidLineNum].IndexOf(',')) || !("RED" == lsAllLines[lastValidLineNum].Split(',')[1] || "PLAY" == lsAllLines[lastValidLineNum].Split(',')[1] || "NEWS PLAY" == lsAllLines[lastValidLineNum].Split(',')[1]) ) { if (0 > lastValidLineNum) { Console.WriteLine("CSV File not valid. Press any key to exit!"); Console.ReadLine(); Application.Exit(); break; } lastValidLineNum--; } if (lsAllLines.Length > unLineCountLastTime && sGadacemisSaxeliLastTime != lsAllLines[lastValidLineNum].Split(',')[4]) { unLineCountLastTime = lsAllLines.Length; string[] arrBoloStriqonisMonacemebi = lsAllLines[lastValidLineNum].Split(','); sGadacemisSaxeliLastTime = TrimFileNameFromUnwantedChars(arrBoloStriqonisMonacemebi[4]); //todo guess name from arrBoloStriqonisMonacemebi[4] sShemdegiGadacemisSaxeli = TrimFileNameFromUnwantedChars( arrBoloStriqonisMonacemebi[4].Substring(arrBoloStriqonisMonacemebi[4].LastIndexOf('\\') + 1)); try { dtAxaliGadacemisDackebisDro = DateTime.ParseExact(arrBoloStriqonisMonacemebi[5] + " " + arrBoloStriqonisMonacemebi[6] //, @"dd\/M\/yyyy HH:mm:ss" , @"M\/d\/yyyy HH:mm:ss" //was dd , CultureProvider); if (dtAxaliGadacemisDackebisDro.Month != DateTime.Now.Month) { dtAxaliGadacemisDackebisDro = DateTime.ParseExact(arrBoloStriqonisMonacemebi[5] + " " + arrBoloStriqonisMonacemebi[6] //, @"dd\/M\/yyyy HH:mm:ss" , @"d\/M\/yyyy HH:mm:ss" , CultureProvider); } } catch (FormatException) { dtAxaliGadacemisDackebisDro = DateTime.ParseExact(arrBoloStriqonisMonacemebi[5] + " " + arrBoloStriqonisMonacemebi[6] //, @"dd\/M\/yyyy HH:mm:ss" , @"dd\/M\/yyyy HH:mm:ss" , CultureProvider); } return(true); } else { sShemdegiGadacemisSaxeli = null; dtAxaliGadacemisDackebisDro = DateTime.Now; return(false); } } catch (WebException) { sShemdegiGadacemisSaxeli = null; dtAxaliGadacemisDackebisDro = DateTime.Now; Console.WriteLine("CSV File not found for current day. "); return(false); } }
private void worker_DoWork(object sender, DoWorkEventArgs e) { /* Create an FTP Request */ ftpRequest = (FtpWebRequest)FtpWebRequest.Create(data.adress + "/" + remoteFile); /* 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.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 */ Directory.CreateDirectory(Path.GetDirectoryName(localFile)); localFileStream = new FileStream(localFile, FileMode.Create); /* Buffer for the Downloaded Data */ byte[] byteBuffer = new byte[bufferSize]; int bytesRead = ftpStream.Read(byteBuffer, 0, bufferSize); int totalBytesRead = bytesRead; /* Download the File by Writing the Buffered Data Until the Transfer is Complete */ while (bytesRead > 0) { if (cancel) { localFileStream.Close(); ftpRequest.Abort(); ftpStream.Close(); ftpResponse.Close(); ftpRequest = null; ftpResponse = null; ftpStream = null; localFileStream = null; e.Cancel = true; return; } localFileStream.Write(byteBuffer, 0, bytesRead); bytesRead = ftpStream.Read(byteBuffer, 0, bufferSize); totalBytesRead += bytesRead; double progress = totalBytesRead * 100.0 / fileSize; WorkerState state = new WorkerState(fileSize, totalBytesRead); worker.ReportProgress((int)progress, state); } /* Resource Cleanup */ localFileStream.Close(); ftpStream.Close(); ftpResponse.Close(); ftpRequest = null; }
/*****************\ * Download file * \*****************/ public void DownloadFile(string remoteFilePath, string localFilePath, double numberOfFiles, BackgroundWorker worker, DoWorkEventArgs e) { //List<object> parameters = e.Argument as List<object>; List<object> returnArguments = new List<object>(); returnArguments.Add("Download"); try { //_DownloadedFileTarget = localFilePath; _DownloadedFilesTarget.Add(localFilePath); if (numberOfFiles == 1) worker.ReportProgress(0); /* Instanciate FTP request */ _FtpRequest = (FtpWebRequest)FtpWebRequest.Create(remoteFilePath); /* Log in */ _FtpRequest.Credentials = new NetworkCredential(_User, _Password); /* Set options */ _FtpRequest.UseBinary = true; _FtpRequest.UsePassive = true; _FtpRequest.KeepAlive = true; /* Specify type of request */ _FtpRequest.Method = WebRequestMethods.Ftp.DownloadFile; /* Establish return communication with ftp server */ _FtpResponse = (FtpWebResponse)_FtpRequest.GetResponse(); using (Stream ftpStream = _FtpResponse.GetResponseStream()) { if (worker.CancellationPending) { e.Cancel = true; } else { /* Open a file stream to write the downloaded file */ FileStream localFileStream = new FileStream(localFilePath, FileMode.Create); /* Buffer for the downloaded data */ byte[] byteBuffer = new byte[_BufferSize]; int bytesRead = ftpStream.Read(byteBuffer, 0, _BufferSize); /* Download the file by writting the buffered data until the transfer is complete */ try { double bytes = 0; while (bytesRead > 0) { if (worker.CancellationPending) { e.Cancel = true; break; } bytes += bytesRead; localFileStream.Write(byteBuffer, 0, bytesRead); bytesRead = ftpStream.Read(byteBuffer, 0, _BufferSize); if (numberOfFiles == 1) worker.ReportProgress(((int)(((bytes / 1000) / _TotalSize) * 100))); } } catch (Exception ex) { returnArguments.Add(ex.ToString()); } /* Ressources cleanup */ localFileStream.Close(); ftpStream.Close(); _FtpResponse.Close(); _FtpRequest = null; } } } catch (Exception ex) { returnArguments.Add(ex.ToString()); } if(numberOfFiles == 1) worker.ReportProgress(100); e.Result = returnArguments; }
public void Download(string remoteFile, string localFile) { try { ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host + "/" + remoteFile); ftpRequest.Credentials = new NetworkCredential(user, pass); ftpRequest.UseBinary = true; ftpRequest.UsePassive = true; ftpRequest.KeepAlive = true; ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile; ftpResponse = (FtpWebResponse)ftpRequest.GetResponse(); ftpStream = ftpResponse.GetResponseStream(); FileStream localFileStream = new FileStream(localFile, FileMode.Create); byte[] byteBuffer = new byte[bufferSize]; int bytesRead = ftpStream.Read(byteBuffer, 0, bufferSize); try { while (bytesRead > 0) { localFileStream.Write(byteBuffer, 0, bytesRead); bytesRead = ftpStream.Read(byteBuffer, 0, bufferSize); } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } localFileStream.Close(); ftpStream.Close(); ftpResponse.Close(); ftpRequest = null; } catch (Exception ex) { Console.WriteLine(ex.ToString()); } return; }
// Connect to and list files from FTP Server public bool LoginCheck() { try { /* Create an FTP Request */ ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host+":"+port); /* 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.ListDirectory; /* Establish Return Communication with the FTP Server */ ftpResponse = (FtpWebResponse)ftpRequest.GetResponse(); /* Get the FTP Server's Response Stream */ 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()); Console.WriteLine(""); Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("========================================"); Console.ResetColor(); Console.WriteLine("Content of the FTP-Server"); Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("========================================"); Console.ResetColor(); foreach (var direct in directoryList) { Console.WriteLine(direct); } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } } catch (Exception) { //Console.WriteLine(ex.ToString()); return false; } return true; }
private string GetStringFromResponseStream(FtpWebRequest ftpRequest) { string result = null; var memoryStream = new MemoryStream(); StreamReader streamReader = null; try { LastResponse = (FtpWebResponse)ftpRequest.GetResponse(); var responseStream = LastResponse.GetResponseStream(); if (TransferData(responseStream, memoryStream)) { streamReader = new StreamReader(memoryStream); memoryStream.Position = 0L; result = streamReader.ReadToEnd(); } } catch (WebException ex) { TestEasyLog.Instance.Info(string.Format("Exception while getting response for '{0}'. Message: '{1}'", ftpRequest.RequestUri, ex.Message)); LastResponse = (FtpWebResponse)ex.Response; } catch (InvalidOperationException ex2) { TestEasyLog.Instance.Info(string.Format("Exception while getting response for '{0}'. Message: '{1}'", ftpRequest.RequestUri, ex2.Message)); } finally { if (LastResponse != null) { LastResponse.Close(); } memoryStream.Close(); if (streamReader != null) { streamReader.Close(); } } return result; }
//Реализеум команду LIST для получения подробного списока файлов на FTP-сервере public FileStruct[] ListDirectory(string path) { if (path == null || path == "") { path = "/"; } //Создаем объект запроса ftpRequest = (FtpWebRequest)WebRequest.Create("ftp://" + _Host + path); //логин и пароль ftpRequest.Credentials = new NetworkCredential(_UserName, _Password); //команда фтп LIST ftpRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails; ftpRequest.EnableSsl = _UseSSL; //Получаем входящий поток ftpResponse = (FtpWebResponse)ftpRequest.GetResponse(); //переменная для хранения всей полученной информации string content = ""; StreamReader sr = new StreamReader(ftpResponse.GetResponseStream(), System.Text.Encoding.ASCII); content = sr.ReadToEnd(); sr.Close(); ftpResponse.Close(); DirectoryListParser parser = new DirectoryListParser(content); return parser.FullListing; }
/* Get the Size of a File */ public string getFileSize(string fileName) { try { /* Create an FTP Request */ ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host + "/" + fileName); /* 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.GetFileSize; /* 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 fileInfo = null; /* Read the Full Response Stream */ try { while (ftpReader.Peek() != -1) { fileInfo = ftpReader.ReadToEnd(); } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } /* Resource Cleanup */ ftpReader.Close(); ftpStream.Close(); ftpResponse.Close(); ftpRequest = null; /* Return File Size */ return fileInfo; } catch (Exception ex) { Console.WriteLine(ex.ToString()); } /* Return an Empty string Array if an Exception Occurs */ return ""; }
/// <summary> /// 从FTP下载文件到本地服务器,支持断点下载 /// </summary> /// <param name="ftpUri">ftp文件路径,如"ftp://localhost/test.txt"</param> /// <param name="saveFile">保存文件的路径,如C:\\test.txt</param> public void BreakPointDownLoadFile(string ftpUri, string saveFile) { System.IO.FileStream fs = null; System.Net.FtpWebResponse ftpRes = null; System.IO.Stream resStrm = null; try { //下载文件的URI Uri u = new Uri(ftpUri); //设定下载文件的保存路径 string downFile = saveFile; //FtpWebRequest的作成 System.Net.FtpWebRequest ftpReq = (System.Net.FtpWebRequest) System.Net.WebRequest.Create(u); //设定用户名和密码 ftpReq.Credentials = new System.Net.NetworkCredential(ftpUser, ftpPassWord); //MethodにWebRequestMethods.Ftp.DownloadFile("RETR")设定 ftpReq.Method = System.Net.WebRequestMethods.Ftp.DownloadFile; //要求终了后关闭连接 ftpReq.KeepAlive = false; //使用ASCII方式传送 ftpReq.UseBinary = false; //设定PASSIVE方式无效 ftpReq.UsePassive = false; //判断是否继续下载 //继续写入下载文件的FileStream if (System.IO.File.Exists(downFile)) { //继续下载 ftpReq.ContentOffset = (new System.IO.FileInfo(downFile)).Length; fs = new System.IO.FileStream( downFile, System.IO.FileMode.Append, System.IO.FileAccess.Write); } else { //一般下载 fs = new System.IO.FileStream( downFile, System.IO.FileMode.Create, System.IO.FileAccess.Write); } //取得FtpWebResponse ftpRes = (System.Net.FtpWebResponse)ftpReq.GetResponse(); //为了下载文件取得Stream resStrm = ftpRes.GetResponseStream(); //写入下载的数据 byte[] buffer = new byte[1024]; while (true) { int readSize = resStrm.Read(buffer, 0, buffer.Length); if (readSize == 0) { break; } fs.Write(buffer, 0, readSize); } } catch (Exception ex) { throw new Exception("从ftp服务器下载文件出错,文件名:" + ftpUri + "异常信息:" + ex.ToString()); } finally { fs.Close(); resStrm.Close(); ftpRes.Close(); } }
public byte[] GetFile(string filePath) { try { /* Create an FTP Request */ ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host + "/" + filePath); /* 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 */ /* 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) { bytesRead = ftpStream.Read(byteBuffer, 0, bufferSize); } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } /* Resource Cleanup */ ftpStream.Close(); ftpResponse.Close(); ftpRequest = null; var nullCount = 0; var listInt = new List<byte>(); var i = 1; foreach (var b in byteBuffer) { if (nullCount < 3) { listInt.Add(b); } if (b == 0 && i == 0) nullCount++; i = b; } return listInt.ToArray(); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } return new byte[1]; }
//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); } }