在C#中,實現斷點續傳功能通常需要使用HttpWebRequest和HttpWebResponse類。以下是一個簡單的示例,展示了如何在C#客戶端中實現斷點續傳功能:
using System;
using System.IO;
using System.Net;
namespace BreakpointResumeExample
{
class Program
{
static void Main(string[] args)
{
string url = "http://example.com/largefile.zip";
string localFilePath = "largefile.zip";
DownloadFileWithBreakpointResume(url, localFilePath);
}
private static void DownloadFileWithBreakpointResume(string url, string localFilePath)
{
long initialPosition = 0;
if (File.Exists(localFilePath))
{
initialPosition = new FileInfo(localFilePath).Length;
}
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.AddRange(initialPosition);
try
{
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
if (response.StatusCode == HttpStatusCode.PartialContent || response.StatusCode == HttpStatusCode.OK)
{
using (Stream remoteStream = response.GetResponseStream())
using (FileStream localStream = new FileStream(localFilePath, FileMode.Append, FileAccess.Write, FileShare.Write))
{
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = remoteStream.Read(buffer, 0, buffer.Length)) > 0)
{
localStream.Write(buffer, 0, bytesRead);
}
}
}
else
{
Console.WriteLine("Error: Server returned status code {0}", response.StatusCode);
}
}
}
catch (Exception ex)
{
Console.WriteLine("Error: {0}", ex.Message);
}
}
}
}
這個示例中,我們首先檢查本地文件是否存在,如果存在,則獲取其長度。然后,我們創建一個HttpWebRequest對象,并設置請求范圍(Range)為初始位置。接下來,我們發送請求并獲取響應。如果服務器返回了部分內容或完整內容,我們將遠程流的數據追加到本地文件流中。
注意:這個示例僅適用于支持斷點續傳的服務器。如果服務器不支持斷點續傳,你可能需要修改代碼以適應不同的服務器行為。