在一个会话中将多个文件上载到FTp服务器

时间:2013-05-28 15:36:14

标签: c# upload ftp

我需要将多个文件上传到ftp服务器,我尝试使用Webrequest一次发送每个文件,问题是我每次发送文件时都需要添加凭据,这意味着我打开了一个新会话。我尝试了不同的方法,但它不起作用,低于我最新的。有谁知道如何优雅地做到这一点?我需要使用一个FTPWebrequest一次发送许多文件,每次发送文件时都没有连接,请考虑这些文件是非常自愿的。有人可以帮我吗?

 private void envoiFTP(string table)
    {
          string path = @"D:\Temp\";
          string[] files = Directory.GetFiles(path,@"*.xml");


          if (files != null)
          {                     
                foreach (string file in files)
                {

                    fi = new FileInfo(file);
                    string fileName = fi.Name;
                    string fileurl = path + @"/" + fileName;
                    string ftpFile = FtpServer + @"/" + fileName;
                    FtpWebRequest myRequest = (FtpWebRequest)FtpWebRequest.Create(ftpFile);

                    myRequest.Credentials = new NetworkCredential(FtpUser, FtpPassword);

                    myRequest.Method = WebRequestMethods.Ftp.UploadFile;
                    myRequest.Timeout = 1000000;
                    myRequest.UseBinary = true;
                    myRequest.KeepAlive = true;


                     myRequest.ContentLength = fi.Length;

                     byte[] buffer = new byte[4097];
                     int bytes = 0;
                     int total_bytes = (int)fi.Length;
                     System.IO.FileStream fs = fi.OpenRead();
                     System.IO.Stream rs = myRequest.GetRequestStream();


                     while (total_bytes > 0)
                     {
                         bytes = fs.Read(buffer, 0, buffer.Length);
                         rs.Write(buffer, 0, bytes);
                         total_bytes = total_bytes - bytes;
                     }

                     fs.Close();
                     rs.Close();

                     FtpWebResponse uploadResponse = (FtpWebResponse)myRequest.GetResponse();
                     uploadResponse.Close();
                }


           } 
                }


            }


    }

0 个答案:

没有答案