c# winform 现实FTP文件上传下载到linux服务器

  • 搭建linux FTP服务器端
  1. 在linux服务器安装vsftp服务器端;
  2. 在linux服务器开启vsftp服务:sudo systemctl start vsftp;
  • 代码实现
  1. 连接服务器
      /// <summary>
        /// 连接ftp方法
        /// </summary>
        /// <param name="path"></param>
        public static void Connect(String path)
        {
            // 根据uri创建FtpWebRequest对象
            objReqFtp = (FtpWebRequest)FtpWebRequest.Create(new Uri(path));
            // 指定数据传输类型
            //To transmit text data, change the UseBinary property from its default value ( true) to false.
            objReqFtp.UseBinary = true;
            // specifies that an SSL connection
            objReqFtp.EnableSsl = false;
            // ftp用户名和密码
            objReqFtp.Credentials = new NetworkCredential(FTPUSERNAME, FTPPASSWORD);
        }
  1. 文件上传到linux服务器(带有上传进度条)
 /// <summary>
 /// 文件上传加进度条
 /// </summary>
 /// <param name="ftpUrl">linux FTP的服务器地址</param>
 /// <param name="filePath">本地文件(文件的绝对路径)</param>
 /// <param name="username">FTP服务器的用户名</param>
 /// <param name="password">FTP服务器的密码</param>
 /// <param name="targetFileName">上传到linux 服务器的文件名</param>
 /// <param name="progressCallback">进度条回调</param>
 public static bool UploadFile(string ftpUrl, string filePath, string username, string password, string targetFileName,Action<int> progressCallback)
 {
     try
     {
         FileInfo fileInfo = new FileInfo(filePath);
         string uri = ftpUrl + targetFileName;

         FtpWebRequest request = (FtpWebRequest)WebRequest.Create(uri);
         request.Method = WebRequestMethods.Ftp.UploadFile;
         request.Credentials = new NetworkCredential(username, password);
         request.ContentLength = fileInfo.Length;

         using (Stream fileStream = fileInfo.OpenRead())
         {
             using (Stream requestStream = request.GetRequestStream())
             {
                 byte[] buffer = new byte[10240];
                 int read;
                 long totalRead = 0;
                 while ((read = fileStream.Read(buffer, 0, buffer.Length)) > 0)
                 {
                     requestStream.Write(buffer, 0, read);
                     totalRead += read;

                     // 计算进度并回调
                     int progress = (int)((totalRead * 100) / fileInfo.Length);
                     progressCallback(progress);
                 }
             }
         }
         return true;
     }
     catch (Exception ex) 
     { 
         return false;
     }            
}

调用方法:

public static string FTPCONSTR = "ftp://服务器IP/data/eqp/eqp_repair_files/";//FTP的服务器地址
var flag = FtpHelp.UploadFile(Ftp服务器地址, 上传本地文件, ftp账号, ftp密码, 文件名, (progress) =>
          {
              this.Invoke((MethodInvoker)delegate
              {
                  progressBar1.Value = progress;  //进度条控件
              });
          });

3.删除FTP服务器文件

  /// <summary>
        /// 删除ftp服务器的文件
        /// </summary>
        /// <param name="url">linux FTP服务器文件信息 eg:ftp://服务器地址(FTP)/data/eqp/eqp_repair_files/CEOLJ130528_机械手损害_20240907163035890.pdf</param>
        /// <returns></returns>
        public static bool DeleteFtpServerFile(string url)
        {
            try
            {
                Connect(url);
                objReqFtp.Method = WebRequestMethods.Ftp.DeleteFile;

                FtpWebResponse response = (FtpWebResponse)objReqFtp.GetResponse();
                response.Close();
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }`

调用方法:
FtpHelp.DeleteFtpServerFile(obj.SFILENAME);

4.从FTP服务器下载文件

 /// <summary>
        /// 从FTP linux服务器下载文件
        /// </summary>
        /// <param name="url">下载文件信息 eg:ftp://服务器地址(FTP)/data/eqp/eqp_repair_files/CEOLJ130528_机械手损害_20240907163035890.pdf</param>
        /// <param name="filePath">下载本地路径</param>
        /// <param name="fileName">下载文件名</param>
        /// <returns></returns>
        public static bool DownloadFromFtpServer(string url, string filePath, string fileName)
        {
            try
            {
                String onlyFileName = Path.GetFileName(fileName);
                string newFileName = filePath + "\\"+onlyFileName;
                if (File.Exists(newFileName))
                {
                    File.Delete(newFileName);//若存在,先刪除
                }

                Connect(url);

                FtpWebResponse response = (FtpWebResponse)objReqFtp.GetResponse();
                Stream ftpStream = response.GetResponseStream();
                long cl = response.ContentLength;
                int bufferSize = 2048;
                int readCount;
                byte[] buffer = new byte[bufferSize];
                readCount = ftpStream.Read(buffer, 0, bufferSize);
                FileStream outputStream = new FileStream(newFileName, FileMode.Create);
                while (readCount > 0)
                {
                    outputStream.Write(buffer, 0, readCount);
                    readCount = ftpStream.Read(buffer, 0, bufferSize);
                }
                ftpStream.Close();
                outputStream.Close();
                response.Close();
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

调用方法:
bool flag=FtpHelp.DownloadFromFtpServer(下载文件信息(文件全路径), 本地文件夹, 下载文件名);

posted on 2024-09-11 17:01  willian知识库  阅读(66)  评论(0)    收藏  举报