/// <summary> /// File 업로드 /// </summary> /// <param name="folder"></param> /// <param name="filename"></param> /// <returns></returns> public Boolean UpLoad(string folder, string filename) { MakeDir(@"/dfs/aaa/bbb/"); // 디렉토리가 없으면 만들기 if (FtpDirectoryExists(@"\AAA") == false) { MakeDir(@"\aaa\dddd\"); } if (FtpDirectoryExists(@"\AAA\") == false) { MakeDir(@"\AAA"); } FileInfo fileInf = new FileInfo(filename); string uri = "ftp://" + ftpServerIP + ":" + ftpPort + "/" + folder + fileInf.Name; uri = "ftp://" + ftpServerIP + ":" + ftpPort + "/" + @"\DFS\abcd\abcd.gls"; FtpWebRequest reqFTP; // Create FtpWebRequest object from the Uri provided reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri)); // Provide the WebPermission Credintials reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); // By default KeepAlive is true, where the control connection is not closed // after a command is executed. reqFTP.KeepAlive = false; // Specify the command to be executed. reqFTP.Method = WebRequestMethods.Ftp.UploadFile; // Specify the data transfer type. reqFTP.UseBinary = true; reqFTP.UsePassive = usePassive; // Notify the server about the size of the uploaded file reqFTP.ContentLength = fileInf.Length; // The buffer size is set to 2kb int buffLength = 2048; byte[] buff = new byte[buffLength]; int contentLen; // Opens a file stream (System.IO.FileStream) to read the file to be uploaded FileStream fs = fileInf.OpenRead(); try { // Stream to which the file to be upload is written Stream strm = reqFTP.GetRequestStream(); // Read from the file stream 2kb at a time contentLen = fs.Read(buff, 0, buffLength); // Till Stream content ends while (contentLen != 0) { // Write Content from the file stream to the FTP Upload Stream strm.Write(buff, 0, contentLen); contentLen = fs.Read(buff, 0, buffLength); } // Close the file stream and the Request Stream strm.Close(); fs.Close(); return(true); } catch (Exception ex) { System.Reflection.MemberInfo info = System.Reflection.MethodInfo.GetCurrentMethod(); string id = string.Format("{0}.{1}", info.ReflectedType.Name, info.Name); if (this.ExceptionEvent != null) { this.ExceptionEvent(id, ex); } return(false); } //catch (Exception ex){MessageBox.Show(ex.Message, "Upload Error");} }
public static void UploadFile(string sourceName, string saveName, string folderPath, ProgressBar progBar, Label lblProgress) { FileInfo fileInf = new FileInfo(sourceName); FtpWebRequest reqFTP; reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpServerPath + "/" + folderPath + "/" + saveName)); reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); reqFTP.KeepAlive = false; reqFTP.Method = WebRequestMethods.Ftp.UploadFile; reqFTP.UseBinary = true; reqFTP.ContentLength = fileInf.Length; int dataLength = (int)reqFTP.ContentLength; int value = 0; int buffLength = 2048; byte[] buff = new byte[buffLength]; int contentLen; FileStream fs = fileInf.OpenRead(); //Set up progress bar if (progBar != null) { progBar.Value = 0; progBar.Maximum = dataLength; } if (lblProgress != null) { lblProgress.Text = "0/" + dataLength.ToString(); } try { Stream strm = reqFTP.GetRequestStream(); contentLen = fs.Read(buff, 0, buffLength); while (contentLen != 0) { strm.Write(buff, 0, contentLen); contentLen = fs.Read(buff, 0, buffLength); //Update the progress bar if (value + contentLen <= dataLength) { value += contentLen; if (progBar != null) { progBar.Value = value; progBar.Refresh(); } if (lblProgress != null) { lblProgress.Text = FormatBytes(value) + "/" + FormatBytes(dataLength); } Application.DoEvents(); } } strm.Close(); fs.Close(); } catch (System.Net.WebException we) { throw new Exception(GetErrMsg(we)); } catch (Exception ex) { throw ex; } }
/// <summary> /// 将输入流作为源头实现FTP上传 /// </summary> /// <param name="package">FTP文件夹</param> /// <param name="fs">文件输入流</param> /// <param name="length">流长度(字节)</param> /// <param name="suffix">上传文件后缀</param> /// <returns>返回上传到ftp服务器的文件名</returns> public string FTPUploadFile(string package, Stream fs, int length, string suffix) { //FTP服务器IP地址 string ftpServerIP = System.Configuration.ConfigurationSettings.AppSettings["ftpIP"].ToString(); //FTP登录用户名 string ftpUserID = System.Configuration.ConfigurationSettings.AppSettings["ftpuser"].ToString(); //FTP登录密码 string ftpPassword = System.Configuration.ConfigurationSettings.AppSettings["ftppasswd"].ToString(); //FTP请求对象 FtpWebRequest ftpRequest = null; //FTP流 Stream ftpStream = null; string fileName = ""; try { fileName = GenerateFileName() + suffix; //创建FtpWebRequest对象 ftpRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + package + "/" + fileName)); //FTP登录 ftpRequest.Credentials = new NetworkCredential(ftpUserID, ftpPassword); // 默认为true,连接不会被关闭 // 在一个命令之后被执行 ftpRequest.KeepAlive = false; //FTP请求执行方法 ftpRequest.Method = WebRequestMethods.Ftp.UploadFile; // 指定数据传输类型 ftpRequest.UseBinary = true; // 上传文件时通知服务器文件的大小 ftpRequest.ContentLength = length; // 缓冲大小设置为2kb int buffLength = 2048 * 10; byte[] buff = new byte[buffLength]; int contentLen; // 把上传的文件写入流 ftpStream = ftpRequest.GetRequestStream(); // 每次读文件流的2kb contentLen = fs.Read(buff, 0, buffLength); // 流内容没有结束 while (contentLen != 0) { // 把内容从file stream 写入 upload stream ftpStream.Write(buff, 0, contentLen); contentLen = fs.Read(buff, 0, buffLength); } Console.WriteLine("上传成功!"); return(fileName); } catch (Exception ex) { Console.WriteLine(ex.Message); SClog.insert("Error", "FtpWEB UpLoad Error --> " + ex.Message + " 文件名:" + fileName); return(""); } finally { if (fs != null) { fs.Close(); } if (ftpStream != null) { ftpStream.Close(); } } }
/// <summary> /// Get the Size of a File /// </summary> /// <param name="fileName"></param> /// <returns></returns> public string GetFileSize(string fileName) { try { /* Store the Raw Response */ string fileInfo = null; /* Create an FTP Request */ FtpWebRequest ftpRequest = (FtpWebRequest)FtpWebRequest.Create(ConnectionString() + "/" + fileName); try { /* Log in to the FTP Server with the User Name and Password Provided */ ftpRequest.Credentials = new NetworkCredential(_username, _password); /* Setup options */ ftpRequest.UseBinary = _useBinary; ftpRequest.UsePassive = _usePassive; ftpRequest.KeepAlive = _keepAlive; /* Specify the Type of FTP Request */ ftpRequest.Method = WebRequestMethods.Ftp.GetFileSize; /* Establish Return Communication with the FTP Server */ FtpWebResponse ftpResponse = (FtpWebResponse)ftpRequest.GetResponse(); try { /* Establish Return Communication with the FTP Server */ Stream ftpStream = ftpResponse.GetResponseStream(); try { /* Get the FTP Server's Response Stream */ StreamReader ftpReader = new StreamReader(ftpStream); try { /* Read the Full Response Stream */ try { while (ftpReader.Peek() != -1) { fileInfo = ftpReader.ReadToEnd(); } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } } finally { ftpReader.Close(); ftpReader.Dispose(); ftpReader = null; } } finally { ftpStream.Close(); ftpStream.Dispose(); ftpStream = null; } } finally { ftpResponse.Close(); ftpResponse = null; } } finally { /* Resource Cleanup */ ftpRequest = null; } /* Return File Size */ return(fileInfo); } catch //(Exception ex) { throw; } }
/// <summary> /// Download File /// </summary> /// <param name="remoteFile"></param> /// <param name="localFile"></param> public void Download(string remoteFile, string localFile) { try { /* Create an FTP Request */ FtpWebRequest ftpRequest = (FtpWebRequest)FtpWebRequest.Create(ConnectionString() + "/" + remoteFile); try { /* Log in to the FTP Server with the User Name and Password Provided */ ftpRequest.Credentials = new NetworkCredential(_username, _password); /* Setup options */ ftpRequest.UseBinary = _useBinary; ftpRequest.UsePassive = _usePassive; ftpRequest.KeepAlive = _keepAlive; /* Specify the Type of FTP Request */ ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile; /* Establish Return Communication with the FTP Server */ FtpWebResponse ftpResponse = (FtpWebResponse)ftpRequest.GetResponse(); try { /* Get the FTP Server's Response Stream */ Stream ftpStream = ftpResponse.GetResponseStream(); try { /* Open a File Stream to Write the Downloaded File */ FileStream localFileStream = new FileStream(localFile, FileMode.Create); try { /* 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()); } } finally { localFileStream.Close(); localFileStream.Dispose(); localFileStream = null; } } finally { ftpStream.Close(); ftpStream.Dispose(); ftpStream = null; } } finally { ftpResponse.Close(); ftpResponse = null; } } finally { /* Resource Cleanup */ ftpRequest = null; } } catch //(Exception ex) { throw; } }
/// <summary> /// ftp方式上传 /// </summary> public static int UploadFtp(string filePath, string filename, string FtpDir, FTP ftpSvr) { string path = ""; if (filePath.Equals("")) { path = filename; } else { path = filePath + "\\" + filename; } FileInfo fileInf = new FileInfo(path); string uri = "ftp://" + ftpSvr.hostname + "/" + FtpDir + "/" + fileInf.Name; FtpWebRequest reqFTP; // Create FtpWebRequest object from the Uri provided reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri)); try { // Provide the WebPermission Credintials reqFTP.Credentials = new NetworkCredential(ftpSvr.username, ftpSvr.password); // By default KeepAlive is true, where the control connection is not closed // after a command is executed. reqFTP.KeepAlive = false; // Specify the command to be executed. reqFTP.Method = WebRequestMethods.Ftp.UploadFile; // Specify the data transfer type. reqFTP.UseBinary = true; // Notify the server about the size of the uploaded file reqFTP.ContentLength = fileInf.Length; // The buffer size is set to 2kb int buffLength = 2048; byte[] buff = new byte[buffLength]; int contentLen; // Opens a file stream (System.IO.FileStream) to read the file to be uploaded //FileStream fs = fileInf.OpenRead(); FileStream fs = fileInf.Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite); // Stream to which the file to be upload is written Stream strm = reqFTP.GetRequestStream(); // Read from the file stream 2kb at a time contentLen = fs.Read(buff, 0, buffLength); // Till Stream content ends while (contentLen != 0) { // Write Content from the file stream to the FTP Upload Stream strm.Write(buff, 0, contentLen); contentLen = fs.Read(buff, 0, buffLength); } // Close the file stream and the Request Stream strm.Close(); fs.Close(); return(0); } catch (Exception ex) { reqFTP.Abort(); // Logging.WriteError(ex.Message + ex.StackTrace); return(-2); } }
//Connects to the FTP server and downloads the file private void downloadFile(string FTPAddress, string filename, string username, string password) { downloadedData = new byte[0]; try { //Optional this.Text = "Connecting..."; Application.DoEvents(); //Create FTP request //Note: format is ftp://server.com/file.ext FtpWebRequest request = FtpWebRequest.Create(FTPAddress + "/" + filename) as FtpWebRequest; //Optional this.Text = "Retrieving Information..."; Application.DoEvents(); //Get the file size first (for progress bar) request.Method = WebRequestMethods.Ftp.GetFileSize; request.Credentials = new NetworkCredential(username, password); request.UsePassive = true; request.UseBinary = true; request.KeepAlive = true; //don't close the connection int dataLength = (int)request.GetResponse().ContentLength; //Optional this.Text = "Downloading File..."; Application.DoEvents(); //Now get the actual data request = FtpWebRequest.Create(FTPAddress + "/" + filename) as FtpWebRequest; request.Method = WebRequestMethods.Ftp.DownloadFile; request.Credentials = new NetworkCredential(username, password); request.UsePassive = true; request.UseBinary = true; request.KeepAlive = false; //close the connection when done //Set up progress bar progressBar1.Value = 0; progressBar1.Maximum = dataLength; lbProgress.Text = "0/" + dataLength.ToString(); //Streams FtpWebResponse response = request.GetResponse() as FtpWebResponse; Stream reader = response.GetResponseStream(); //Download to memory //Note: adjust the streams here to download directly to the hard drive MemoryStream memStream = new MemoryStream(); byte[] buffer = new byte[1024]; //downloads in chuncks while (true) { Application.DoEvents(); //prevent application from crashing //Try to read the data int bytesRead = reader.Read(buffer, 0, buffer.Length); if (bytesRead == 0) { //Nothing was read, finished downloading progressBar1.Value = progressBar1.Maximum; lbProgress.Text = dataLength.ToString() + "/" + dataLength.ToString(); Application.DoEvents(); break; } else { //Write the downloaded data memStream.Write(buffer, 0, bytesRead); //Update the progress bar if (progressBar1.Value + bytesRead <= progressBar1.Maximum) { progressBar1.Value += bytesRead; lbProgress.Text = progressBar1.Value.ToString() + "/" + dataLength.ToString(); progressBar1.Refresh(); Application.DoEvents(); } } } //Convert the downloaded stream to a byte array downloadedData = memStream.ToArray(); //Clean up reader.Close(); memStream.Close(); response.Close(); MessageBox.Show("Downloaded Successfully"); } catch (Exception) { MessageBox.Show("There was an error connecting to the FTP Server."); } txtData.Text = downloadedData.Length.ToString(); this.Text = "Download Data through FTP"; username = string.Empty; password = string.Empty; }
public String UploadFile(String fichero, String destino, String dir) { dir = dir.Replace("\\", "/"); destino = destino.Replace("\\", "/"); FileInfo infoFichero = new FileInfo(fichero); // Si no existe el directorio, lo creamos if (ExistsFile(dir)) { MakeDir(System.Web.HttpUtility.UrlEncode(dir)); } // Creamos una peticion FTP con la dirección del fichero que vamos a subir FtpWebRequest peticionFTP = (FtpWebRequest)FtpWebRequest.Create(GetUri(destino)); // Fijamos el usuario y la contraseña de la petición peticionFTP.Credentials = new NetworkCredential(_user, _pass); // Seleccionamos el comando que vamos a utilizar: Subir un fichero peticionFTP.Method = WebRequestMethods.Ftp.UploadFile; peticionFTP.KeepAlive = false; peticionFTP.UsePassive = false; peticionFTP.UseBinary = true; // Informamos al servidor sobre el tamaño del fichero que vamos a subir try { peticionFTP.ContentLength = infoFichero.Length; } catch (Exception ex) { return(ex.Message); } // Fijamos un buffer de 2KB int longitudBuffer; longitudBuffer = 2048; Byte[] lector = new Byte[2048]; // esti estaba Byte (2048); int num; // Abrimos el fichero para subirlo FileStream fs; fs = infoFichero.OpenRead(); Stream escritor = null; try { escritor = peticionFTP.GetRequestStream(); // Leemos 2 KB del fichero en cada iteración num = fs.Read(lector, 0, longitudBuffer); // num=fs.Read (lector[],0,longitudBuffer); while (num != 0) { // Escribimos el contenido del flujo de lectura en el // flujo de escritura del comando FTP escritor.Write(lector, 0, num); num = fs.Read(lector, 0, longitudBuffer); } escritor.Close(); fs.Close(); //Si todo ha ido bien, se devolverá String.Empty return(String.Empty); } catch (WebException ex) { if (escritor == null) { escritor.Close(); } fs.Close(); // Si se produce algún fallo, se devolverá el mensaje del error return(ex.Message); } }
/// <summary> /// Download background worker /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void DownloadFiles_DoWork(object sender, DoWorkEventArgs e) { if (this.cancelProcess) { e.Cancel = true; return; } // specify the URL of the file to download string url = this.ftpAddress + this.downloadUrls.Peek().Replace('\\', '/'); // specify the output file name int outputFileArraySize = this.downloadUrls.Peek().Split('\\').Length; string outputFile = this.downloadUrls.Peek().Split('\\')[outputFileArraySize - 1]; // looks for tfr if (outputFile.Contains("task_force_radio")) { this.isTFR = true; } // auxiliary variables string outputComplete = AddonsFolder + this.downloadUrls.Peek(); string downloadSpeed = string.Empty; int progressPercentage = 0; // ftp login client.Credentials = networkCredential; // get the size of the file to download ftpRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(url)); ftpRequest.Method = WebRequestMethods.Ftp.GetFileSize; ftpRequest.Credentials = networkCredential; ftpResponse = (FtpWebResponse)ftpRequest.GetResponse(); Int64 bytesTotal = Convert.ToInt64(ftpResponse.ContentLength); ftpResponse.Close(); // download the file and write it to disk using (Stream stream = client.OpenRead(new Uri(url))) using (FileStream file = new FileStream(outputComplete, FileMode.Create)) { var buffer = new byte[32768]; int bytesRead; Int64 bytesReadComplete = 0; // use Int64 for files larger than 2 gb // start a new StartWatch for measuring download time Stopwatch sw = Stopwatch.StartNew(); // download file in chunks while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) != 0) { if (this.cancelProcess) { e.Cancel = true; break; } bytesReadComplete += bytesRead; parsedBytes += bytesRead; file.Write(buffer, 0, bytesRead); if ((bytesReadComplete / 1024d / sw.Elapsed.TotalSeconds) > 999) { downloadSpeed = String.Format("{0:F1} mb/s", bytesReadComplete / 1048576d / sw.Elapsed.TotalSeconds); } else { downloadSpeed = String.Format("{0:F1} kb/s", bytesReadComplete / 1024d / sw.Elapsed.TotalSeconds); } progressPercentage = Convert.ToInt32(((double)bytesReadComplete / bytesTotal) * 100); this.progressBarFileStyle(ProgressBarStyle.Continuous); this.progressBarFileValue(progressPercentage); this.progressBarAllValue(Convert.ToInt32(((double)parsedBytes / totalBytes) * 100)); this.progressStatusText(String.Format("Downloading ({0:F0}/{1:F0}) {2}... {3:F0}%", this.parsedDownloads, this.totalDownloads, outputFile, progressPercentage)); this.progressDetailsText(String.Format("{0:0}MB of {1:0}MB / {2}", ConvertBytesToMegabytes(bytesReadComplete), ConvertBytesToMegabytes(bytesTotal), downloadSpeed)); } sw.Stop(); } }
public static void Download(string file, string ftpuri, string UID, string PWD, string path) { try { string uri = ftpuri + file; Uri serverUri = new Uri(uri); if (serverUri.Scheme != Uri.UriSchemeFtp) { return; } FileInfo localFileInfo = new FileInfo(path + "/" + file); var local_Info = localFileInfo.LastWriteTime; FtpWebRequest reqFTP1; reqFTP1 = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpuri + file)); reqFTP1.Credentials = new NetworkCredential(UID, PWD); reqFTP1.KeepAlive = false; // reqFTP.Method = WebRequestMethods.Ftp.DownloadFile; reqFTP1.Method = WebRequestMethods.Ftp.GetDateTimestamp; reqFTP1.UseBinary = true; reqFTP1.Proxy = null; FtpWebResponse response1 = (FtpWebResponse)reqFTP1.GetResponse(); var server_Info = response1.LastModified; response1.Close(); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } if (File.Exists(path + "/" + file)) // Check Modified Files { if (server_Info > local_Info) // Assumed it was extended { goto Down; } else { return; } } Down: if (File.Exists(path + "/" + file)) // Check Modified Files { File.Delete(path + "/" + file); } FtpWebRequest reqFTP; reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpuri + file)); reqFTP.Credentials = new NetworkCredential(UID, PWD); reqFTP.KeepAlive = false; reqFTP.Method = WebRequestMethods.Ftp.DownloadFile; reqFTP.UseBinary = true; reqFTP.Proxy = null; FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse(); Stream responseStream = response.GetResponseStream(); FileStream writeStream = new FileStream(path + "/" + file, FileMode.Create); int Length = 2048; Byte[] buffer = new Byte[Length]; int bytesRead = responseStream.Read(buffer, 0, Length); while (bytesRead > 0) { writeStream.Write(buffer, 0, bytesRead); bytesRead = responseStream.Read(buffer, 0, Length); } writeStream.Close(); response.Close(); File.SetLastWriteTime(path + "/" + file, server_Info); //} //Delete //FtpWebRequest requestFileDelete = (FtpWebRequest)WebRequest.Create("ftp://202.223.48.145/" + file); //requestFileDelete.Credentials = new NetworkCredential("Administrator", "c@p!+A1062O"); //requestFileDelete.Method = WebRequestMethods.Ftp.DeleteFile; //FtpWebResponse responseFileDelete = (FtpWebResponse)requestFileDelete.GetResponse(); } catch { //MessageBox.Show(ex.Message, "Download Error"); } }
/** * Get the files. */ private FtpFileInfo[] GetFiles(KexplorerFtpNode knode) { ArrayList files = new ArrayList(); string ftpfullpath = "ftp://" + kNode.Site.host + knode.Path; FtpWebResponse ftpResponse = null; FtpWebRequest ftp = null; try { ftp = (FtpWebRequest)FtpWebRequest.Create(ftpfullpath); ftp.Credentials = new NetworkCredential(kNode.Site.username, kNode.Site.pwd); //userid and password for the ftp server to given ftp.KeepAlive = true; ftp.UseBinary = true; ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails; ftpResponse = (FtpWebResponse)ftp.GetResponse(); Stream responseStream = null; responseStream = ftpResponse.GetResponseStream(); string strFile = null; try { StreamReader reader = new StreamReader(responseStream); while (true) { strFile = null; try { strFile = reader.ReadLine(); } catch (IOException e) { break; } if (strFile != null) { FtpFileInfo newFileInfo = new FtpFileInfo(strFile, kNode.Site.type); if (!newFileInfo.isDir) { files.Add(newFileInfo); } } else { break; } } } catch (Exception e) { String x = e.Message; } try { ftpResponse.Close(); } catch (Exception e) { } } catch (WebException e) { return(null); } finally { if (ftpResponse != null) { ftpResponse.Close(); } } return((FtpFileInfo[])files.ToArray(typeof(FtpFileInfo))); }
/// <summary> /// 获取ftp服务器上指定文件夹的文件列表(包含文件大小) /// </summary> /// <param name="ServerIP"></param> /// <param name="USERID"></param> /// <param name="PassWord"></param> /// <param name="path"></param> /// <returns></returns> public static void GetFTPFileInfo(string url, string USERID, string PassWord, Action <Dictionary <string, long> > callback) { Dictionary <string, long> dic = new Dictionary <string, long>(); FtpWebRequest reqFtp; try { getFtpFileInfoThread = new Thread(() => { // reqFtp = (FtpWebRequest)FtpWebRequest.Create(new Uri(url)); reqFtp.KeepAlive = false; reqFtp.UseBinary = true; //指定ftp数据传输类型为 二进制 reqFtp.Credentials = new NetworkCredential(USERID, PassWord); //设置于ftp通讯的凭据 //reqFtp.Method = WebRequestMethods.Ftp.GetFileSize; reqFtp.Method = WebRequestMethods.Ftp.ListDirectoryDetails; //指定操作方式 WebResponse response = reqFtp.GetResponse(); //获取一个FTP响应 StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8); //读取响应流 string line = reader.ReadLine(); reader.Dispose(); response.Close(); reqFtp.Abort(); if (line != "." && !string.IsNullOrEmpty(line)) { int end = line.LastIndexOf(' '); int start = line.IndexOf(" "); string filename = line.Substring(end + 1); if (filename.Contains(".")) { line = line.Replace(filename, ""); var strPart = line.Substring(start).Trim(); var strSize = strPart.Split(new char[] { ' ' }); var strSizeSinge = strSize[3]; if (string.IsNullOrEmpty(strSize[3])) { strSizeSinge = strSize[4]; } if (string.IsNullOrEmpty(strSize[4])) { strSizeSinge = strSize[5]; } if (string.IsNullOrEmpty(strSize[5])) { strSizeSinge = strSize[6]; } if (string.IsNullOrEmpty(strSize[6])) { strSizeSinge = strSize[7]; } if (!string.IsNullOrEmpty(strSizeSinge)) { long intSize = Convert.ToInt64(strSizeSinge); dic.Add(filename.Trim(), intSize); } } } callback(dic); getFtpFileInfoThread.Abort(); }); getFtpFileInfoThread.Start(); } catch (Exception ex) { LogManage.WriteLog(typeof(FtpManage), ex); } }
/// <summary> /// 文件后上传 /// </summary> /// <param name="FileName">待上传的文件</param> /// <param name="ftpRoot">ftp上传路径</param> /// <param name="ftpUser">用户名称</param> /// <param name="ftpPassword">密码</param> /// <returns></returns> public void UploadFtp(string FileName, string ftpRoot, string ftpUser, string ftpPassword, Action <long, double> callback, Action <Exception, bool> compleateCallback) { Thread thread = new Thread(new ThreadStart(() => { FileInfo fileInf = new FileInfo(FileName); string uri = ftpRoot + "/" + fileInf.Name; _reqFTPUp = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri)); try { _reqFTPUp.Credentials = new NetworkCredential(ftpUser, ftpPassword); _reqFTPUp.KeepAlive = true; _reqFTPUp.Method = WebRequestMethods.Ftp.UploadFile; _reqFTPUp.UseBinary = true; _reqFTPUp.ContentLength = fileInf.Length; int buffLength = 2048; byte[] buff = new byte[buffLength]; int contentLen; _fsUp = fileInf.Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite); _strmUp = _reqFTPUp.GetRequestStream(); contentLen = _fsUp.Read(buff, 0, buffLength); //后台工作者,实时更新ui控件值 _workerUp = new BackgroundWorker(); double length = 0; _workerUp.ProgressChanged += (object sender, ProgressChangedEventArgs e) => { try { length += e.ProgressPercentage; callback(_fsUp.Length, length); } catch (Exception ex) { this.FtpUpLoadClose(); compleateCallback(ex, false); } }; _workerUp.RunWorkerCompleted += (object sender, RunWorkerCompletedEventArgs e) => { this.FtpUpLoadClose(); compleateCallback(null, true); }; //BackgroundWorker.WorkerReportsProgress 获取或设置一个值,该值指示 BackgroundWorker 能否报告进度更新。 _workerUp.WorkerReportsProgress = true; _workerUp.DoWork += (obj, e) => { while (contentLen != 0) { _strmUp.Write(buff, 0, contentLen); contentLen = _fsUp.Read(buff, 0, buffLength); //每次上传一个文件更新一次 ((BackgroundWorker)obj).ReportProgress(contentLen); } }; //后台工作者开始工作(开始执行DoWork) _workerUp.RunWorkerAsync(); } catch (Exception ex) { _reqFTPUp.Abort(); compleateCallback(ex, false); } })); thread.Start(); }
/// <summary> /// 文件下载 /// </summary> /// <param name="fileRoot"></param> /// <param name="ftpUrl"></param> /// <param name="ftpUser"></param> /// <param name="ftpPassword"></param> /// <returns></returns> public void DownloadFtp(string fileRoot, string ftpUrl, string ftpUser, string ftpPassword, Action <long, double> callback, Action <Exception, bool> compleateCallback) { _thread = new Thread(new ThreadStart(() => { try { var file = ftpUrl.Substring(ftpUrl.LastIndexOf("/") + 1); _outputStreamDown = new FileStream(fileRoot + "\\" + file, FileMode.Create); _reqFTPDown = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpUrl)); _reqFTPDown.Method = WebRequestMethods.Ftp.DownloadFile; _reqFTPDown.UseBinary = true; _reqFTPDown.KeepAlive = false; _reqFTPDown.Credentials = new NetworkCredential(ftpUser, ftpPassword); _responseDown = (FtpWebResponse)_reqFTPDown.GetResponse(); Stream ftpStream = _responseDown.GetResponseStream(); long cl = _responseDown.ContentLength; int bufferSize = 512; int readCount; byte[] buffer = new byte[bufferSize]; readCount = ftpStream.Read(buffer, 0, bufferSize); //后台工作者,实时更新ui控件值 _workerDown = new BackgroundWorker(); if (_workerDown.IsBusy) { _workerDown.CancelAsync(); } double length = 0; if (callback != null) { //更新事件 _workerDown.ProgressChanged += (object sender, ProgressChangedEventArgs e) => { length += e.ProgressPercentage; callback(cl, length); }; } if (compleateCallback != null) { //更新完毕 _workerDown.RunWorkerCompleted += (object sender, RunWorkerCompletedEventArgs e) => { ftpStream.Close(); _outputStreamDown.Close(); _responseDown.Close(); compleateCallback(null, true); }; } //BackgroundWorker.WorkerReportsProgress 获取或设置一个值,该值指示 BackgroundWorker 能否报告进度更新。 _workerDown.WorkerReportsProgress = true; _workerDown.DoWork += (obj, e) => { Thread.Sleep(500); while (readCount > 0) { _outputStreamDown.Write(buffer, 0, readCount); readCount = ftpStream.Read(buffer, 0, bufferSize); //每次上传一个文件更新一次 ((BackgroundWorker)obj).ReportProgress(readCount); } }; //后台工作者开始工作(开始执行DoWork) _workerDown.RunWorkerAsync(); // } catch (Exception ex) { compleateCallback(ex, false); } })); _thread.Start(); }
/* List Directory Contents File/Folder Name Only */ public string[] directoryListSimple(string directory) { List <String> listing = new List <String>(); try { /* Create an FTP Request */ String ftpAddress = host + "/" + directory; ftpRequest = (FtpWebRequest)FtpWebRequest.Create(ftpAddress); // + "/" + directory); /* Log in to the FTP Server with the User Name and Password Provided */ //ftpRequest.Credentials = new NetworkCredential(user, ""); ftpRequest.Credentials = new NetworkCredential(this.user, this.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(); /* 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) { listing.Add(ex.Message); 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()); listing = directoryList.ToList(); } catch (Exception ex) { listing.Add(String.Format("Error 1: {0}", ex.Message)); Console.WriteLine(ex.ToString()); } } catch (Exception ex) { listing.Add(String.Format("Error 2: {0}", ex.Message)); Console.WriteLine(ex.ToString()); } /* Return an Empty string Array if an Exception Occurs */ return(listing.ToArray()); }
/* Upload File */ public string Upload(string remoteFile, string localFile) { string status = string.Empty; /* 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; ftpRequest.EnableSsl = enableSSL; /* Specify the Type of FTP Request */ ftpRequest.Method = WebRequestMethods.Ftp.UploadFile; /* Establish Return Communication with the FTP Server */ ftpStream = ftpRequest.GetRequestStream(); /* Open a File Stream to Read the File for Upload */ FileStream localFileStream = new FileStream(localFile, FileMode.Open); /* Buffer for the Downloaded Data */ byte[] byteBuffer = new byte[bufferSize]; int bytesSent = localFileStream.Read(byteBuffer, 0, bufferSize); /* Upload the File by Sending the Buffered Data Until the Transfer is Complete */ try { while (bytesSent != 0) { ftpStream.Write(byteBuffer, 0, bytesSent); bytesSent = localFileStream.Read(byteBuffer, 0, bufferSize); } } catch (WebException ex) { //string errDet = ExceptionFormatter.GetFormattedExceptionDetails(ex); status = ((FtpWebResponse)ex.Response).StatusDescription; //_error.Error(errDet, ex); } catch (Exception ex) { status = ex.Message; //string errDet = ExceptionFormatter.GetFormattedExceptionDetails(ex); //_error.Error(errDet, ex); } finally { /* Resource Cleanup */ localFileStream.Close(); if (ftpStream != null) { ftpStream.Close(); } ftpRequest = null; } return(status); }
private void Upload(string filename) { try { FileInfo fileInf = new FileInfo(filename); string uri = "ftp://" + txtserverip.Text + "/" + fileInf.Name; // txtUpload.Text =fileInf.Name; // Create FtpWebRequest object from the Uri provided reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + txtserverip.Text + "/" + fileInf.Name)); // Provide the WebPermission Credintials reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); // By default KeepAlive is true, where the control connection is not closed // after a command is executed. reqFTP.KeepAlive = false; // Specify the command to be executed. reqFTP.Method = WebRequestMethods.Ftp.UploadFile; // Specify the data transfer type. reqFTP.UseBinary = true; // Notify the server about the size of the uploaded file reqFTP.ContentLength = fileInf.Length; // The buffer size is set to 2kb int buffLength = 2048; byte[] buff = new byte[buffLength]; int contentLen; // Opens a file stream (System.IO.FileStream) to read the file to be uploaded FileStream fs = fileInf.OpenRead(); try { // Stream to which the file to be upload is written Stream strm = reqFTP.GetRequestStream(); // Read from the file stream 2kb at a time contentLen = fs.Read(buff, 0, buffLength); // Till Stream content ends while (contentLen != 0) { // Write Content from the file stream to the FTP Upload Stream strm.Write(buff, 0, contentLen); contentLen = fs.Read(buff, 0, buffLength); } // Close the file stream and the Request Stream strm.Close(); fs.Close(); } catch (Exception ex) { Page.ClientScript.RegisterStartupScript(this.GetType(), "click", "alert('Upload error!');"); } } catch (Exception x) { } }
public void Ftp_Init(string SourceFolder, string WebConfig, string Domain) { var IISFTPUser = "******"; var IISFTPPassword = "******"; //create folder var WebsiteFTPUser = "******"; var WebsiteFTPPassword = "******"; FtpWebRequest reqFTP = null; Stream ftpStream = null; //string[] subDirs = _domain.DomainName.Split('/'); string currentDir = "ftp://[email protected]:23/"; //foreach (string subDir in subDirs) //{ try { currentDir = currentDir + "/" + Domain; reqFTP = (FtpWebRequest)FtpWebRequest.Create(currentDir); reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory; reqFTP.UseBinary = true; reqFTP.Credentials = new NetworkCredential(WebsiteFTPUser, WebsiteFTPPassword); FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse(); ftpStream = response.GetResponseStream(); ftpStream.Close(); response.Close(); } catch (Exception ex) { //directory already exist I know that is weak but there is no way to check if a folder exist on ftp... } //} //hosting mappingjbd string filePath = "~/" + "Docs/applicationHost.Config"; //Server path WebClient client = new WebClient(); client.Credentials = new NetworkCredential(IISFTPUser, IISFTPPassword); client.DownloadFile("ftp://[email protected]/applicationHost.config", filePath); // Write string path = filePath; XmlDocument xDoc = new XmlDocument(); xDoc.Load(path); XmlNodeList nodeList = xDoc.GetElementsByTagName("sites"); XmlNode newNode = xDoc.CreateElement("site"); nodeList[0].AppendChild(newNode); int id = 0; XmlNodeList nodeAppSettings = nodeList[0].ChildNodes; for (int i = 0; i < nodeList[0].ChildNodes.Count - 1; i++) { if (nodeList[0].ChildNodes[i].Name.ToLower() == "site".ToLower()) { if (Convert.ToInt32(nodeList[0].ChildNodes[i].Attributes[1].Value) > id) { id = Convert.ToInt32(nodeList[0].ChildNodes[i].Attributes[1].Value); } } } id = id + 1; int COUNT = nodeAppSettings.Count - 1; XmlNode node = nodeAppSettings[COUNT]; XmlAttribute att = xDoc.CreateAttribute("name"); att.InnerText = Domain; node.Attributes.Append(att); XmlAttribute att2 = xDoc.CreateAttribute("id"); att2.InnerText = id.ToString(); node.Attributes.Append(att2); node.InnerXml = @"<application path='/' applicationPool='DefaultAppPool'> <virtualDirectory path = '/' physicalPath = '" + "publish Code path" + @"' /> </application> <bindings> <binding protocol ='http' bindingInformation= '*:80:" + Domain + @"' /> </bindings> "; xDoc.Save(path); // saves the web.config file //Upload client.Credentials = new NetworkCredential(IISFTPUser, IISFTPPassword); client.UploadFile("ftp://[email protected]/applicationHost.config", filePath); }
public void Upload(string filename, string host, string username, string password) { FileInfo fileInf = new FileInfo(filename); long size = fileInf.Length; //string uri = "ftp://" + host + "/" + fileInf.Name; FtpWebRequest reqFTP = default(FtpWebRequest); // Create FtpWebRequest object from the Uri provided string tenfile = fileInf.Name; string[] tenfiles = tenfile.Split('.'); tenfile = tenfiles[0]; if (tenfile != "") { tenfile = ConvertStringToUnSign(txtNhaCC.Text.Trim()); } tenfile = tenfile + "." + tenfiles[1]; string uri = "ftp://" + host + "/" + tenfile + ""; UriBuilder newUriPort = new UriBuilder(uri); newUriPort.Port = 2121; uri = newUriPort.Uri.ToString(); reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri)); // Provide the WebPermission Credintials reqFTP.Credentials = new NetworkCredential(username, password); // By default KeepAlive is true, where the control connection is not closed // after a command is executed. reqFTP.KeepAlive = false; // Specify the command to be executed. reqFTP.Method = WebRequestMethods.Ftp.UploadFile; // Specify the data transfer type. reqFTP.UseBinary = true; // Notify the server about the size of the uploaded file reqFTP.ContentLength = fileInf.Length; // The buffer size is set to 2kb int buffLength = 2048; byte[] buff = new byte[buffLength]; int contentLen = 0; // Opens a file stream (System.IO.FileStream) to read the file to be uploaded FileStream fs = fileInf.OpenRead(); try { // Stream to which the file to be upload is written Stream strm = reqFTP.GetRequestStream(); // Read from the file stream 2kb at a time contentLen = fs.Read(buff, 0, buffLength); // Till Stream content ends while (contentLen != 0) { // Write Content from the file stream to the FTP Upload Stream strm.Write(buff, 0, contentLen); contentLen = fs.Read(buff, 0, buffLength); } // Close the file stream and the Request Stream strm.Close(); fs.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message, "Upload image Error"); } }
private void refreshFiles(StringBuilder path) { fileName.Text = "--"; fileType.Text = "--"; fileSize.Text = "--"; pathTextBox.Text = Convert.ToString(path); directoryList.Items.Clear(); List <string> files = new List <string>(); try { FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(Convert.ToString(path)); request.Method = WebRequestMethods.Ftp.ListDirectory; request.Credentials = new NetworkCredential("", ""); request.UsePassive = true; request.UseBinary = true; request.KeepAlive = false; FtpWebResponse response = (FtpWebResponse)request.GetResponse(); Stream responseStream = response.GetResponseStream(); StreamReader reader = new StreamReader(responseStream); while (!reader.EndOfStream) { Application.DoEvents(); files.Add(reader.ReadLine()); } reader.Close(); responseStream.Close(); response.Close(); } catch (Exception) { MessageBox.Show("There was an error connecting to the FTP Server"); } if (files.Count != 0) { String ext; foreach (String file in files) { if (file.Contains('.')) { ext = file.Substring(file.LastIndexOf("."), file.Length - file.LastIndexOf(".")); switch (ext) { case ".mp3": case ".mp": directoryList.Items.Add(file, 1); break; case ".mp4": case ".avi": case ".mkv": directoryList.Items.Add(file, 2); break; case ".jpeg": case ".jpg": case ".png": directoryList.Items.Add(file, 3); break; case ".pdf": directoryList.Items.Add(file, 4); break; case ".txt": directoryList.Items.Add(file, 5); break; case ".apk": directoryList.Items.Add(file, 6); break; case ".zip": case ".rar": case ".7z": directoryList.Items.Add(file, 7); break; case ".exe": directoryList.Items.Add(file, 8); break; case ".ppt": case ".pptx": directoryList.Items.Add(file, 9); break; case ".doc": case ".docx": directoryList.Items.Add(file, 10); break; default: directoryList.Items.Add(file, 11); break; } } else { directoryList.Items.Add(file, 0); } } } }
/// <summary> /// Upload File /// </summary> /// <param name="remoteFile"></param> /// <param name="localFile"></param> public void Upload(string remoteFile, string localFile) { try { /* Open a File Stream to Read the File for Upload */ FileStream localFileStream = new FileStream(localFile, FileMode.Open); try { /* Create an FTP Request */ FtpWebRequest ftpRequest = (FtpWebRequest)FtpWebRequest.Create(ConnectionString() + "/" + remoteFile); try { /* Log in to the FTP Server with the User Name and Password Provided */ ftpRequest.Credentials = new NetworkCredential(_username, _password); /* Setup options */ ftpRequest.UseBinary = _useBinary; ftpRequest.UsePassive = _usePassive; ftpRequest.KeepAlive = _keepAlive; /* Specify the Type of FTP Request */ ftpRequest.Method = WebRequestMethods.Ftp.UploadFile; /* Establish Return Communication with the FTP Server */ Stream ftpStream = ftpRequest.GetRequestStream(); try { /* Buffer for the Downloaded Data */ byte[] byteBuffer = new byte[_bufferSize]; long fileSize = Utilities.FileSize(localFile); long totalSent = 0; bool cancelled = false; RaiseFileUploadStart(localFile, fileSize); int bytesSent = localFileStream.Read(byteBuffer, 0, _bufferSize); try { /* Upload the File by Sending the Buffered Data Until the Transfer is Complete */ while (bytesSent != 0) { ftpStream.Write(byteBuffer, 0, bytesSent); bytesSent = localFileStream.Read(byteBuffer, 0, _bufferSize); totalSent += bytesSent; if (!RaiseFileUpload(localFile, totalSent)) { cancelled = true; break; } } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } finally { RaiseFileUploadFinish(localFile, totalSent, cancelled); } } finally { ftpStream.Close(); ftpStream.Dispose(); ftpStream = null; } } finally { /* Resource Cleanup */ ftpRequest = null; } } finally { localFileStream.Close(); localFileStream.Dispose(); localFileStream = null; } } catch //(Exception ex) { throw; } return; }
/// <summary> /// получение списка файлов /// </summary> /// <param name="context"></param> /// <returns></returns> protected override bool Execute(CodeActivityContext context) { string ftpURL = null; string username = null; string password = null; string folder; string port = null; ftpURL = context.GetValue(FTPUrl); username = context.GetValue(Username); password = context.GetValue(Password); folder = context.GetValue(Folder); port = context.GetValue(Port); try { if (!(ftpURL.StartsWith("ftp"))) { ftpURL = "ftp://" + ftpURL; } if (!(port.EndsWith("/"))) { port += "/"; } if (!(port.StartsWith(":"))) { port = ":" + port; } if (!string.IsNullOrEmpty(folder)) { if (!(folder.EndsWith("/"))) { folder += "/"; } } string fullURL = ftpURL + port + folder; if (!(fullURL.EndsWith("/"))) { fullURL += "/"; } FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(fullURL); request.Method = WebRequestMethods.Ftp.ListDirectoryDetails; request.Credentials = new NetworkCredential(username, password); request.UsePassive = true; request.UseBinary = true; request.KeepAlive = false; List <FtpDirectoryItem> returnValue = new List <FtpDirectoryItem>(); string[] list = null; using (FtpWebResponse response = (FtpWebResponse)request.GetResponse()) { using (StreamReader reader = new StreamReader(response.GetResponseStream())) { list = reader.ReadToEnd().Split(new string[] { "\r\n" }, StringSplitOptions.None);//RemoveEmptyEntries); } } foreach (string line in list) { if (string.IsNullOrEmpty(line)) { continue; } #region не работает 1 ////http://stackoverflow.com/questions/25246426/extracting-file-names-from-webrequestmethods-ftp-listdirectorydetails //string regex = // @"^" + //# Start of line // @"(?<dir>[\-ld])" + //# File size // @"(?<permission>[\-rwx]{9})" + //# Whitespace \n // @"\s+" + //# Whitespace \n // @"(?<filecode>\d+)" + // @"\s+" + //# Whitespace \n // @"(?<owner>\w+)" + // @"\s+" + //# Whitespace \n // @"(?<group>\w+)" + // @"\s+" + //# Whitespace \n // @"(?<size>\d+)" + // @"\s+" + //# Whitespace \n // @"(?<month>\w{3})" + //# Month (3 letters) \n // @"\s+" + //# Whitespace \n // @"(?<day>\d{1,2})" + //# Day (1 or 2 digits) \n // @"\s+" + //# Whitespace \n // @"(?<timeyear>[\d:]{4,5})" + //# Time or year \n // @"\s+" + //# Whitespace \n // @"(?<filename>(.*))" + //# Filename \n // @"$"; //var split = new Regex(regex).Match(line); //string dir = split.Groups["dir"].ToString(); //string filename = split.Groups["filename"].ToString(); //bool isDirectory = !string.IsNullOrWhiteSpace(dir) && dir.Equals("d", StringComparison.OrdinalIgnoreCase); #endregion #region вариант 2 //Regex FtpListDirectoryDetailsRegex = new Regex(@".*(?<month>(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec))\s*(?<day>[0-9]*)\s*(?<yearTime>([0-9]|:)*)\s*(?<fileName>.*)", RegexOptions.Compiled | RegexOptions.IgnoreCase); //string ftpResponse = "-r--r--r-- 1 ftp ftp 0 Nov 19 11:08 aaa.txt"; //Match match = FtpListDirectoryDetailsRegex.Match(ftpResponse); //string month = match.Groups["month"].Value; //string day = match.Groups["day"].Value; //string yearTime = match.Groups["yearTime"].Value; //string fileName = match.Groups["fileName"].Value; ////Using ListDirectoryDetails should yield a line starting with "-" or "d" ////I have not seen a scenario when either characters are not present. "d" == directory, "-" == file ////http://www.seesharpdot.net/?p=242 #endregion // Windows FTP Server Response Format // DateCreated IsDirectory Name string data = line; // Parse date string date = data.Substring(0, 17); DateTime dateTime = DateTime.Parse(date, System.Globalization.CultureInfo.CreateSpecificCulture("en-US").DateTimeFormat); //DateTime.Parse(date); data = data.Remove(0, 24); // Parse <DIR> string dir = data.Substring(0, 5); bool isDirectory = dir.Equals("<dir>", StringComparison.InvariantCultureIgnoreCase); if (isDirectory) { continue; } data = data.Remove(0, 5); data = data.Remove(0, 10); // Parse name string filename = data; // Create directory info FtpDirectoryItem item = new FtpDirectoryItem { BaseUri = new Uri(fullURL), DateCreated = dateTime, IsDirectory = isDirectory, StringName = filename }; //Debug.WriteLine(item.AbsolutePath); //без подпапок //item.Items = item.IsDirectory ? Execute(item.AbsolutePath, username, password) : null; returnValue.Add(item); } FileList.Set(context, returnValue); } catch (Exception ex) { Error.Set(context, ex.Message); } return(string.IsNullOrEmpty(Error.Get(context))); }
/// <summary> /// List Directory Contents in Detail (Name, Size, Created, etc.) /// </summary> /// <param name="directory"></param> /// <returns></returns> public string[] DirectoryListDetailed(string directory) { try { /* Store the Raw Response */ string directoryRaw = null; /* Create an FTP Request */ FtpWebRequest ftpRequest = (FtpWebRequest)FtpWebRequest.Create(ConnectionString() + "/" + directory); try { /* Log in to the FTP Server with the User Name and Password Provided */ ftpRequest.Credentials = new NetworkCredential(_username, _password); /* Setup options */ ftpRequest.UseBinary = _useBinary; ftpRequest.UsePassive = _usePassive; ftpRequest.KeepAlive = _keepAlive; /* Specify the Type of FTP Request */ ftpRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails; /* Establish Return Communication with the FTP Server */ FtpWebResponse ftpResponse = (FtpWebResponse)ftpRequest.GetResponse(); try { /* Establish Return Communication with the FTP Server */ Stream ftpStream = ftpResponse.GetResponseStream(); try { /* Get the FTP Server's Response Stream */ StreamReader ftpReader = new StreamReader(ftpStream); try { /* 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()); } } finally { /* Resource Cleanup */ ftpReader.Close(); ftpReader.Dispose(); ftpReader = null; } } finally { ftpStream.Close(); ftpStream.Dispose(); ftpStream = null; } } finally { ftpResponse.Close(); ftpResponse = null; } } finally { /* Resource Cleanup */ ftpRequest = null; } /* Return the Directory Listing as a string Array by Parsing 'directoryRaw' with the Delimiter you Append (I use | in This Example) */ try { return(directoryRaw.Split("|".ToCharArray())); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } } catch //(Exception ex) { throw; } /* Return an Empty string Array if an Exception Occurs */ return(new string[] { "" }); }
/// <summary> /// Get ftp file /// </summary> /// <returns></returns> public string Get(string remotefileName, string savefileName, string savePath) { string ftpFilePath = string.Empty; string StoragePath = string.Empty; FtpWebRequest ftpRequest = null; NetworkCredential ftpCredential = null; FtpWebResponse ftpResponse = null; Stream ftpStream = null; try { if (!Directory.Exists(savePath)) { Directory.CreateDirectory(savePath); } ftpFilePath = FTPAddress + RemotePath + remotefileName; StoragePath = savePath + "/" + savefileName; ftpRequest = (FtpWebRequest)FtpWebRequest.Create(ftpFilePath); ftpCredential = new NetworkCredential(UserID, UserPW); ftpRequest.Credentials = ftpCredential; ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile; ftpResponse = (FtpWebResponse)ftpRequest.GetResponse(); ftpStream = ftpResponse.GetResponseStream(); using (FileStream fileStream = new FileStream(StoragePath, FileMode.Create)) { int bufferSize = 2048; int readCount; byte[] buffer = new byte[bufferSize]; readCount = ftpStream.Read(buffer, 0, bufferSize); while (readCount > 0) { fileStream.Write(buffer, 0, readCount); readCount = ftpStream.Read(buffer, 0, bufferSize); } } ftpStream.Close(); ftpResponse.Close(); } catch (Exception ex) { throw new Exception(ex.ToString()); } finally { if (ftpStream != null) { ftpStream.Close(); } if (ftpResponse != null) { ftpResponse.Close(); } } return(StoragePath); }
public static void UploadFile(string filename) { FileInfo fileInf = new FileInfo(filename); //string uri = "ftp://" + ftpServerPath + "/" + fileInf.Name; FtpWebRequest reqFTP; // Create FtpWebRequest object from the Uri provided reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpServerPath + "/" + fileInf.Name)); // Provide the WebPermission Credintials reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); // By default KeepAlive is true, where the control connection is not closed // after a command is executed. reqFTP.KeepAlive = false; // Specify the command to be executed. reqFTP.Method = WebRequestMethods.Ftp.UploadFile; // Specify the data transfer type. reqFTP.UseBinary = true; // Notify the server about the size of the uploaded file reqFTP.ContentLength = fileInf.Length; // The buffer size is set to 2kb int buffLength = 2048; byte[] buff = new byte[buffLength]; int contentLen; // Opens a file stream (System.IO.FileStream) to read the file to be uploaded FileStream fs = fileInf.OpenRead(); try { // Stream to which the file to be upload is written Stream strm = reqFTP.GetRequestStream(); // Read from the file stream 2kb at a time contentLen = fs.Read(buff, 0, buffLength); // Till Stream content ends while (contentLen != 0) { // Write Content from the file stream to the FTP Upload Stream strm.Write(buff, 0, contentLen); contentLen = fs.Read(buff, 0, buffLength); } // Close the file stream and the Request Stream strm.Close(); fs.Close(); } catch (System.Net.WebException we) { throw new Exception(GetErrMsg(we)); } catch (Exception ex) { throw ex; } }
public bool UploadToFTP(MemoryStream ms, string filename) { this.ProgressBar.Start(filename, ms.Length); string strPath = ftpPath; if (!strPath.EndsWith("/")) { strPath += "/"; } FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create("ftp://" + ftpServer + strPath + filename); ftp.Proxy = null; //TODO: Ftp Proxy? (From SO: "If the specified proxy is an HTTP proxy, only the DownloadFile, ListDirectory, and ListDirectoryDetails commands are supported.") ftp.Credentials = new NetworkCredential(ftpUsername, ftpPassword); ftp.Method = WebRequestMethods.Ftp.UploadFile; ftp.UsePassive = ftpPassive; ftp.UseBinary = ftpBinary; Stream stream = ftp.GetRequestStream(); int sr = 1024; for (int i = 0; i < ms.Length; i += 1024) { if (ms.Length - i < 1024) { sr = (int)ms.Length - i; } else { sr = 1024; } byte[] buffer = new byte[sr]; ms.Seek((long)i, SeekOrigin.Begin); ms.Read(buffer, 0, sr); stream.Write(buffer, 0, sr); if (this.ProgressBar.Canceled) { // Remove the file from the server.. //TODO: Make this a setting? FtpWebRequest ftpDelete = (FtpWebRequest)FtpWebRequest.Create("ftp://" + ftpServer + strPath + filename); ftpDelete.Proxy = null; ftpDelete.Method = WebRequestMethods.Ftp.DeleteFile; ftpDelete.Credentials = ftp.Credentials; ftpDelete.UsePassive = ftpPassive; ftpDelete.UseBinary = ftpBinary; ftpDelete.GetResponse(); ftpDelete.Abort(); ftp.Abort(); ms.Dispose(); ftp = null; ms = null; return(false); } this.ProgressBar.Set(i); } stream.Close(); stream.Dispose(); ftp.Abort(); this.ProgressBar.Done(); return(true); }
public static void DownloadFile(string localPath, string saveName, string ftpFilePath, ProgressBar progBar, Label lblProgress) { try { //Create FTP request FtpWebRequest request = FtpWebRequest.Create(ftpServerPath + "/" + ftpFilePath) as FtpWebRequest; //Get the file size first (for progress bar) request.Method = WebRequestMethods.Ftp.GetFileSize; request.Credentials = new NetworkCredential(ftpUserID, ftpPassword); request.UsePassive = true; request.UseBinary = true; request.KeepAlive = true; //don't close the connection int dataLength = (int)request.GetResponse().ContentLength; int value = 0; //Now get the actual data request = FtpWebRequest.Create(ftpServerPath + "/" + ftpFilePath) as FtpWebRequest; request.Method = WebRequestMethods.Ftp.DownloadFile; request.Credentials = new NetworkCredential(ftpUserID, ftpPassword); request.UsePassive = true; request.UseBinary = true; request.KeepAlive = false; //close the connection when done //Set up progress bar if (progBar != null) { progBar.Value = 0; progBar.Maximum = dataLength; } if (lblProgress != null) { lblProgress.Text = "0/" + dataLength.ToString(); } //Streams FtpWebResponse response = request.GetResponse() as FtpWebResponse; Stream reader = response.GetResponseStream(); //Download to memory //Note: adjust the streams here to download directly to the hard drive FileStream fileStream = new FileStream(localPath + "\\" + saveName, FileMode.Create); byte[] buffer = new byte[1024]; //downloads in chuncks while (true) { Application.DoEvents(); //prevent application from crashing //Try to read the data int bytesRead = reader.Read(buffer, 0, buffer.Length); if (bytesRead == 0) { //Nothing was read, finished downloading if (progBar != null) { progBar.Value = progBar.Maximum; } if (lblProgress != null) { lblProgress.Text = FormatBytes(dataLength) + "/" + FormatBytes(dataLength); } Application.DoEvents(); break; } else { //Write the downloaded data fileStream.Write(buffer, 0, bytesRead); //Update the progress bar if (value + bytesRead <= dataLength) { value += bytesRead; if (progBar != null) { progBar.Value = value; progBar.Refresh(); } if (lblProgress != null) { lblProgress.Text = FormatBytes(value) + "/" + FormatBytes(dataLength); } Application.DoEvents(); } } } //Clean up reader.Close(); fileStream.Close(); response.Close(); } catch (System.Net.WebException we) { throw new Exception(GetErrMsg(we)); } catch (Exception ex) { throw ex; } }
bool UploadFile(string filename) { string ftpServerIP = "37.194.254.25"; string ftpUserName = "******"; string ftpPassword = "******"; FileInfo objFile = new FileInfo(filename); FtpWebRequest objFTPRequest; // Create FtpWebRequest object string remoteFileName = string.Format("{0}", objFile.Name); remoteFileName = remoteFileName.Replace(" ", "+"); objFTPRequest = (FtpWebRequest)FtpWebRequest.Create( new Uri("ftp://" + ftpServerIP + "/" + remoteFileName)); // Set Credintials objFTPRequest.Credentials = new NetworkCredential(ftpUserName, ftpPassword); // By default KeepAlive is true, where the control connection is // not closed after a command is executed. objFTPRequest.KeepAlive = false; // Set the data transfer type. objFTPRequest.UseBinary = true; // Set content length objFTPRequest.ContentLength = objFile.Length; // Set request method objFTPRequest.Method = WebRequestMethods.Ftp.UploadFile; // Set buffer size int intBufferLength = 16 * 1024; byte[] objBuffer = new byte[intBufferLength]; try { // Opens a file to read using (FileStream objFileStream = objFile.OpenRead()) { Log("Установка соединения..."); // Get Stream of the file using (Stream objStream = objFTPRequest.GetRequestStream()) { int len = 0; Int64 total = 0; int last_done_percent = 0; while ((len = objFileStream.Read(objBuffer, 0, intBufferLength)) != 0) { if (stopIt) { return(false); } // Write file Content objStream.Write(objBuffer, 0, len); total += len; int done_percent = (int)(100 * total / objFile.Length); if (last_done_percent != done_percent) { last_done_percent = done_percent; Log(string.Format("Отправлено: {0}%", done_percent)); } } } } } catch (Exception ex) { Log(string.Format("Ошибка загрузки файла.\n{0}", ex.ToString())); return(false); } Log("Файл успешно отправлен!"); return(true); }
/// <summary> /// FTP下载文件 /// </summary> /// <param name="ftpServerIP">FTP服务器IP</param> /// <param name="ftpUserID">FTP登录帐号</param> /// <param name="ftpPassword">FTP登录密码</param> /// <param name="saveFilePath">保存文件路径</param> /// <param name="saveFileName">保存文件名</param> /// <param name="downloadFileName">下载文件名</param> public void FTPDownloadFile(string ftpServerIP, string ftpUserID, string ftpPassword, string saveFilePath, string saveFileName, string downloadFileName) { //定义FTP请求对象 FtpWebRequest ftpRequest = null; //定义FTP响应对象 FtpWebResponse ftpResponse = null; //存储流 FileStream saveStream = null; //FTP数据流 Stream ftpStream = null; try { //生成下载文件 saveStream = new FileStream(saveFilePath + "\\" + saveFileName, FileMode.Create); //生成FTP请求对象 ftpRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + downloadFileName)); //设置下载文件方法 ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile; //设置文件传输类型 ftpRequest.UseBinary = true; //设置登录FTP帐号和密码 ftpRequest.Credentials = new NetworkCredential(ftpUserID, ftpPassword); //生成FTP响应对象 ftpResponse = (FtpWebResponse)ftpRequest.GetResponse(); //获取FTP响应流对象 ftpStream = ftpResponse.GetResponseStream(); //响应数据长度 long cl = ftpResponse.ContentLength; int bufferSize = 2048; int readCount; byte[] buffer = new byte[bufferSize]; //接收FTP文件流 readCount = ftpStream.Read(buffer, 0, bufferSize); while (readCount > 0) { saveStream.Write(buffer, 0, readCount); readCount = ftpStream.Read(buffer, 0, bufferSize); } Console.WriteLine("下载成功!"); } catch (Exception ex) { Console.WriteLine(ex.Message); SClog.insert("Error", "FtpWEB DownLoad Error --> " + ex.Message + " 下载路径:" + saveFilePath + " 保存文件名:" + saveFileName + " 下载文件名:" + downloadFileName); } finally { if (ftpStream != null) { ftpStream.Close(); } if (saveStream != null) { saveStream.Close(); } if (ftpResponse != null) { ftpResponse.Close(); } } }
private async void btnGenOferta_Click(object sender, RoutedEventArgs e) { var list = dgProd.Items.OfType <Producto>(); Boolean pass = false; if (list.Count() > 0) { foreach (var item in list) { if (item.Selec == true) { pass = true; } } if (pass) { ServiceReference1.Service1Client proxy = new ServiceReference1.Service1Client(); Oferta of = new Oferta(); string nombreImagen = txtNombre.Text + "_" + DateTime.Now.ToString(); var listaSuc = dgSuc.Items.OfType <Sucursal>(); OfertaHasSucursal ohs = new OfertaHasSucursal(); int contOK = 0; of.ImagenOferta = nombreImagen; of.MinProductos = int.Parse(txtMinProd.Text); of.MaxProductos = int.Parse(txtMaxProd.Text); of.PrecioAntes = int.Parse(txtPrecioAntes.Text); of.PrecioOferta = int.Parse(txtPrecio.Text); if (chPubOf.IsChecked == true) { of.EstadoOferta = char.Parse(1.ToString()); } else { of.EstadoOferta = char.Parse(0.ToString()); } of.FechaOferta = dpFecha.SelectedDate; of.IdSucursal = mainwindow.UsuarioACtual.IdSucursal; of.CategoriaIdOferta = (int)cbCatOf.SelectedValue; of.Nombre = txtNombre.Text; of.Descripcion = txtDescOf.Text; of.OfertaDia = char.Parse("1"); string json = of.Serializar(); if (proxy.CrearOferta(json)) { // inserta tablaaproducto has ofertas ProductoHasOferta pho = new ProductoHasOferta(); foreach (var item in list) { if (item.Selec == true) { pho.OfertaId = of.IdOferta; pho.ProductoId = item.IdProducto; string jerson = pho.Serializar(); proxy.CrearProductoHasOferta(jerson); } } // inserta tabla Oferta Has sucursal foreach (var itemSuc in listaSuc) { if (itemSuc.Selec == true) { ohs.OfertaId = of.IdOferta; ohs.SucursalId = itemSuc.IdSucursal; string jeson = ohs.Serializar(); proxy.CrearOfertaHasSucursal(jeson); contOK++; } } /*Envia por ftp imagen adjuntada*/ string user = "******"; string pw = "789456123"; string FTP = "ftp://adonisweb.cl/" + nombreImagen; FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(FTP); request.Method = WebRequestMethods.Ftp.UploadFile; request.Credentials = new NetworkCredential(user, pw); request.UsePassive = true; request.UseBinary = true; request.KeepAlive = true; FileStream stream = File.OpenRead(rutaNombreImagenOferta); byte[] buffer = new byte[stream.Length]; stream.Read(buffer, 0, buffer.Length); stream.Close(); Stream reqStream = request.GetRequestStream(); reqStream.Write(buffer, 0, buffer.Length); reqStream.Flush(); reqStream.Close(); if (contOK > 0) { await this.ShowMessageAsync("Exito", "Oferta creada para " + contOK + " sucursales!"); } else { await this.ShowMessageAsync("Error", "No se pudo crear la oferta"); } LimpiarControles(); contOK = 0; } } else { await this.ShowMessageAsync("Error", "Debe seleccionar uno o mas productos de la lista"); } } else { await this.ShowMessageAsync("Error", "Debe buscar almenos un producto en la lista"); } }