C# FTP斷點續(xù)傳上傳文件實現(xiàn)代碼
當(dāng)前位置:點晴教程→知識管理交流
→『 技術(shù)文檔交流 』
在C#中進(jìn)行FTP斷點續(xù)傳上傳文件的過程如下所示:
以下是一個基本的示例代碼片段,展示了如何在C#中實現(xiàn)FTP斷點續(xù)傳上傳文件: using System; using System.IO; using System.Net;
class Program { static void Main(string[] args) { string ftpServer = "ftp://example.com"; // FTP服務(wù)器地址 string username = "username"; // FTP登錄用戶名 string password = "password"; // FTP登錄密碼
string localFilePath = @"C:\path\to\localfile.txt"; // 本地文件路徑 string remoteDirectory = "/remote/directory/"; // 遠(yuǎn)程目錄路徑 string fileName = Path.GetFileName(localFilePath); // 文件名稱
try { using (var fileStream = File.OpenRead(localFilePath)) { var requestUriBuilder = new UriBuilder(ftpServer + remoteDirectory + fileName);
if (!IsRemoteFileExists(requestUriBuilder.ToString(), username, password)) { UploadWholeFile(requestUriBuilder.ToString(), fileStream, username, password); } else { long uploadedSize = GetUploadedSize(requestUriBuilder.ToString());
if (uploadedSize > 0 && uploadedSize < fileStream.Length) { ResumeUploadFromPosition(requestUriBuilder.ToString(), fileStream, uploadedSize, username, password); } else { Console.WriteLine("The file is already fully uploaded."); } } }
Console.WriteLine("File upload completed successfully!"); } catch (Exception ex) { Console.WriteLine($"An error occurred during the file upload process: {ex}"); } }
private static bool IsRemoteFileExists(string url, string userName, string password) { var request = (FtpWebRequest)WebRequest.Create(url); request.Method = WebRequestMethods.Ftp.ListDirectoryDetails; request.Credentials = new NetworkCredential(userName, password);
try { using (var response = (FtpWebResponse)request.GetResponse()) { return true; } } catch (WebException) { return false; } }
private static 該文章在 2024/1/12 16:21:56 編輯過 |
關(guān)鍵字查詢
相關(guān)文章
正在查詢... |