在c#中将多个文件上传到FTP

问题描述 投票:1回答:1

我正在使用以下方法将文件从本地服务器上传到FTP服务器,这里我正在创建一个新连接并启动一个新会话,每个文件上传和关闭相同。如何在c#中的单个启动会话中实现此目的。

这是我的代码

public bool UploadTempFilesToFTP()
    {
        string[] fileList;
        try
        {
            ConfiguredValues conObj = new ConfiguredValues();
            conObj.PickTheValuesFromConfigFile();
            fileList = Directory.GetFiles(conObj.tempPath);
            foreach (string FileName in fileList)
            {
                FtpWebRequest upldrequest = (FtpWebRequest)FtpWebRequest.Create(conObj.tempOutboundURL + FileName);


                upldrequest.UseBinary = true;
                upldrequest.KeepAlive = false;
                upldrequest.Timeout = -1;
                upldrequest.UsePassive = true;

                upldrequest.Credentials = new NetworkCredential(conObj.user, conObj.pass);

                upldrequest.Method = WebRequestMethods.Ftp.UploadFile;

                string destinationAddress = conObj.tempPath;

                FileStream fs = File.OpenRead(destinationAddress + FileName);
                byte[] buffer = new byte[fs.Length];
                fs.Read(buffer, 0, buffer.Length);
                fs.Close();
                Stream requestStr = upldrequest.GetRequestStream();
                requestStr.Write(buffer, 0, buffer.Length);
                requestStr.Close();
                requestStr.Flush();
                FtpWebResponse response = (FtpWebResponse)upldrequest.GetResponse();
                response.Close();
                File.Delete(destinationAddress + FileName);
            }
            Console.WriteLine("Uploaded Successfully to Temp folder");
            return true;
        }
        catch (Exception ex)
        {
            Console.WriteLine("Upload failed. {0}", ex.Message);
            return false;
        }

    } 
c# ftp
1个回答
1
投票

ftp协议旨在根据请求进行工作。

您使用方法(在您的情况下为UploadFile)启动请求。

您唯一能做的就是KeepAlive您的请求,以避免连接关闭

upldrequest.KeepAlive = true;

在您创建的每个请求中,除了最后一个请求。这将使登录只有第一个FTPWebRequest

然后当你创建最后一个FTPWebRequest时,设置

upldrequest.KeepAlive = false;

完成后它将关闭连接。

© www.soinside.com 2019 - 2024. All rights reserved.