c#/用ftp上传文件的更有效方法

时间:2016-01-18 18:10:12

标签: c# ftp timeout

我使用c#和

上传.txt文件

client.Credentials = new NetworkCredential(ftpU, ftpP); client.UploadFile("here ftp server", "STOR", lfilepath);

有时它只会抛出错误,例如"系统错误"

此.txt只是登录信息,此txt的内容类似于User: Name At: 2015/12/12 08:43 AM

有没有消除此错误的选项?使ftp上传更有效?或任何想在Internet上保存登录信息的想法。

1 个答案:

答案 0 :(得分:0)

尝试使用 FtpWebRequest WebRequestMethods.Ftp.UploadFile 。以下是我们用于将文件从ZipArchive上传到FTP的代码段(因此,如果您需要,还可以显示创建目录的选项)。从我测试的所有方法来看,它是最有效的方法。

//// Get the object used to communicate with the server.
var request =
    (FtpWebRequest)
        WebRequest.Create("ftp://" + ftpServer + @"/" + remotePath + @"/" +
                          entry.FullName.TrimEnd('/'));

//// Determine if we are transferring file or directory
if (string.IsNullOrWhiteSpace(entry.Name) && !string.IsNullOrWhiteSpace(entry.FullName))
    request.Method = WebRequestMethods.Ftp.MakeDirectory;
else
    request.Method = WebRequestMethods.Ftp.UploadFile;

//// Try to transfer file
try
{
    //// This example assumes the FTP site uses anonymous logon.
    request.Credentials = new NetworkCredential(user, password);

    switch (request.Method)
    {
        case WebRequestMethods.Ftp.MakeDirectory:
            break;

        case WebRequestMethods.Ftp.UploadFile:
            var buffer = new byte[8192];
            using (var rs = request.GetRequestStream())
            {
                StreamUtils.Copy(entry.Open(), rs, buffer);
            }

            break;
    }
}
catch (Exception ex)
{
    //// Handle it!
    LogHelper.Error<FtpHelper>("Could not extract file from package.", ex);
}
finally
{
    //// Get the response from the FTP server.
    var response = (FtpWebResponse) request.GetResponse();

    //// Close the connection = Happy a FTP server.
    response.Close();
}