c# ftp上传下载

上传代码:

public void upLoad(string localFileName, string folderName, string ReportID)
        {
            NetworkCredential nCredl = new NetworkCredential("ftpuser", "53v61M3j");
            FtpWebRequest ftpQ = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://hl-tmi.com/hms/" + folderName + "/" + ReportID + ".pdf"));
            ftpQ.KeepAlive = false;
            ftpQ.UseBinary = true;
            ftpQ.Credentials = nCredl;
            ftpQ.Method = WebRequestMethods.Ftp.UploadFile;
            int buffLength = 2048;  ////
            byte[] buff = new byte[buffLength];
            FileInfo file = new FileInfo(localFileName);
            FileStream fs = file.OpenRead();
            try
            {
                Stream strm = ftpQ.GetRequestStream();
                int contentLen = fs.Read(buff, 0, buffLength);
                int allbye = (int)file.Length;
                while (contentLen != 0)
                {
                    strm.Write(buff, 0, contentLen);
                    contentLen = fs.Read(buff, 0, buffLength);
                }
                // 关闭两个流
                strm.Close();
                fs.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message+"\r\n"+ex.StackTrace);
            }
        }

 下载代码:

public static string returnFilePath(string folderName, string ReportID)
        {
            try
            {
                NetworkCredential nCredl = new NetworkCredential("ftpuser", "53v61M3j");
                FtpWebRequest ftpQ = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://hl-tmi.com/hms/" + folderName + "/" + ReportID + ".pdf"));
                ftpQ.KeepAlive = false;
                ftpQ.UseBinary = true;
                ftpQ.Credentials = nCredl;
                ftpQ.Method = WebRequestMethods.Ftp.DownloadFile;

                FtpWebResponse response = (FtpWebResponse)ftpQ.GetResponse();
                long cl = response.ContentLength;
                string returnPath = @"" + Application.StartupPath + "\\downFromFtp.pdf";
                if (File.Exists(returnPath))
                {
                    File.Delete(returnPath);
                }
                Stream responseStream = response.GetResponseStream();
                FileStream filestream = new FileStream(returnPath, FileMode.Create, FileAccess.Write);
                int buflength = 8196;
                byte[] buffer = new byte[buflength];
                int bytesRead = 1;             
                while (bytesRead != 0)
                {
                    bytesRead = responseStream.Read(buffer, 0, buflength);
                    filestream.Write(buffer, 0, bytesRead);
                }
                filestream.Close();
 
                return returnPath;
            }
            catch (Exception)
            {
                return "";
            }
        }

 

posted @ 2018-10-17 14:17  风影我爱罗  阅读(183)  评论(0编辑  收藏  举报