How to continue or resume FTP upload after interruption of internet

99封情书 提交于 2019-12-17 20:34:08

问题


I am using below code (C# .NET 3.5) to upload a file:

FtpWebRequest request =
    (FtpWebRequest)WebRequest.Create("ftp://someweb.mn/altanzulpharm/file12.zip");
request.Method = WebRequestMethods.Ftp.UploadFile;
request.KeepAlive = true;
request.UseBinary = true;
request.Credentials = new NetworkCredential(username, password);

FileStream fs = File.OpenRead(FilePath);
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
fs.Close();

Stream ftpstream = request.GetRequestStream();
ftpstream.Write(buffer, 0, buffer.Length);
ftpstream.Close();

But the upload breaks when internet interrupted. Interruption occurs for a very small amount of time, almost a millisecond. But uploading breaks forever!

Is it possible to continue or resume uploading after interruption of internet?


回答1:


I don't believe FtpWebRequest supports re-connection after losing connection. You can resume upload from given position if server supports it (this support is not required and presumably less common that retry for download).

You'll need to set FtpWebRequet.ContentOffset upload. Part of sample from the article:

FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverUri);
request.ContentOffset = offset;

Internal details of restore in FTP protocol itself - RFC959: 3.5 - Error recovery and restart. Question showing retry code for download - Downloading from FTP with c#, can't retry when fail




回答2:


The only way to resume transfer after a connection is interrupted with FtpWebRequest, is to reconnect and start writing to the end of the file.

For that use FtpWebRequest.ContentOffset.


Or use an FTP library that can resume the transfer automatically.

For example WinSCP .NET assembly does. With it, a resumable upload is as trivial as:

# Load WinSCP .NET assembly
Add-Type -Path "WinSCPnet.dll"

# Setup session options
$sessionOptions = New-Object WinSCP.SessionOptions -Property @{
    Protocol = [WinSCP.Protocol]::Ftp
    HostName = "ftp.example.com"
    UserName = "user"
    Password = "mypassword"
}

$session = New-Object WinSCP.Session

# Connect
$session.Open($sessionOptions)

# Resumable upload
$transferResult = $session.PutFiles("C:\path\file.zip", "/home/user/file.zip").Check()

(I'm the author of WinSCP)



来源:https://stackoverflow.com/questions/41779788/how-to-continue-or-resume-ftp-upload-after-interruption-of-internet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!