网络中断后如何继续或恢复 FTP 上传

11

本文介绍了网络中断后如何继续或恢复 FTP 上传的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我正在使用以下代码 (C# .NET 3.5) 上传文件:

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?

推荐答案

FtpWebRequest中断连接后恢复传输的唯一方法是重新连接并开始写入文件末尾.

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.

为此使用 FtpWebRequest.ContentOffset.

完整代码上传的相关问题(尽管针对 C#):
如何在断开连接的情况下自动恢复下载FTP文件

A related question for upload with full code (although for C#):
How to download FTP files with automatic resume in case of disconnect

或者使用可以自动恢复传输的 FTP 库.

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

例如 WinSCP .NET 程序集.有了它,可恢复的上传就变得如此简单:

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

// Setup session options
var sessionOptions = new SessionOptions
{
    Protocol = Protocol.Ftp,
    HostName = "ftp.example.com",
    UserName = "user",
    Password = "mypassword"
};

using (var session = new Session())
{
    // Connect
    session.Open(sessionOptions);

    // Resumable upload
    session.PutFileToDirectory(@"C:pathfile.zip", "/home/user");
}

(我是 WinSCP 的作者)

这篇关于网络中断后如何继续或恢复 FTP 上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

C# 中的多播委托奇怪行为?
Multicast delegate weird behavior in C#?(C# 中的多播委托奇怪行为?)...
2023-11-11 C#/.NET开发问题
6

参数计数与调用不匹配?
Parameter count mismatch with Invoke?(参数计数与调用不匹配?)...
2023-11-11 C#/.NET开发问题
26

如何将代表存储在列表中
How to store delegates in a List(如何将代表存储在列表中)...
2023-11-11 C#/.NET开发问题
6

代表如何工作(在后台)?
How delegates work (in the background)?(代表如何工作(在后台)?)...
2023-11-11 C#/.NET开发问题
5

没有 EndInvoke 的 C# 异步调用?
C# Asynchronous call without EndInvoke?(没有 EndInvoke 的 C# 异步调用?)...
2023-11-11 C#/.NET开发问题
2

Delegate.CreateDelegate() 和泛型:错误绑定到目标方法
Delegate.CreateDelegate() and generics: Error binding to target method(Delegate.CreateDelegate() 和泛型:错误绑定到目标方法)...
2023-11-11 C#/.NET开发问题
14