最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

C# FTP調(diào)用的實現(xiàn)示例

 更新時間:2025年11月17日 11:17:47   作者:猩火燎猿  
本文介紹了.NET平臺實現(xiàn)FTP/SFTP操作的多種方案,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧

1. 使用 .NET 自帶 FtpWebRequest 實現(xiàn) FTP 操作

1.1 文件上傳

using System.Net;
using System.IO;
 
public void UploadFile(string ftpUrl, string username, string password, string localFile, string remoteFile)
{
    string url = $"{ftpUrl}/{remoteFile}";
    FtpWebRequest request = (FtpWebRequest)WebRequest.Create(url);
    request.Method = WebRequestMethods.Ftp.UploadFile;
    request.Credentials = new NetworkCredential(username, password);
 
    byte[] fileContents = File.ReadAllBytes(localFile);
    request.ContentLength = fileContents.Length;
 
    using (Stream requestStream = request.GetRequestStream())
    {
        requestStream.Write(fileContents, 0, fileContents.Length);
    }
    using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
    {
        Console.WriteLine($"上傳狀態(tài): {response.StatusDescription}");
    }
}

1.2 文件下載

public void DownloadFile(string ftpUrl, string username, string password, string remoteFile, string localFile)
{
    string url = $"{ftpUrl}/{remoteFile}";
    FtpWebRequest request = (FtpWebRequest)WebRequest.Create(url);
    request.Method = WebRequestMethods.Ftp.DownloadFile;
    request.Credentials = new NetworkCredential(username, password);
 
    using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
    using (Stream responseStream = response.GetResponseStream())
    using (FileStream fs = new FileStream(localFile, FileMode.Create))
    {
        responseStream.CopyTo(fs);
    }
}

1.3 列出目錄和文件

public void ListDirectory(string ftpUrl, string username, string password)
{
    FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpUrl);
    request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
    request.Credentials = new NetworkCredential(username, password);
 
    using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
    using (Stream responseStream = response.GetResponseStream())
    using (StreamReader reader = new StreamReader(responseStream))
    {
        string line;
        while ((line = reader.ReadLine()) != null)
        {
            Console.WriteLine(line);
        }
    }
}

1.4 刪除文件和目錄

public void DeleteFile(string ftpUrl, string username, string password, string remoteFile)
{
    string url = $"{ftpUrl}/{remoteFile}";
    FtpWebRequest request = (FtpWebRequest)WebRequest.Create(url);
    request.Method = WebRequestMethods.Ftp.DeleteFile;
    request.Credentials = new NetworkCredential(username, password);
 
    using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
    {
        Console.WriteLine($"刪除狀態(tài): {response.StatusDescription}");
    }
}
 
public void DeleteDirectory(string ftpUrl, string username, string password, string remoteDir)
{
    string url = $"{ftpUrl}/{remoteDir}";
    FtpWebRequest request = (FtpWebRequest)WebRequest.Create(url);
    request.Method = WebRequestMethods.Ftp.RemoveDirectory;
    request.Credentials = new NetworkCredential(username, password);
 
    using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
    {
        Console.WriteLine($"刪除目錄狀態(tài): {response.StatusDescription}");
    }
}

2. 進階:斷點續(xù)傳(部分實現(xiàn))

.NET標準庫不直接支持FTP斷點續(xù)傳,但可以通過設置 ContentOffset 實現(xiàn)下載斷點續(xù)傳

public void ResumeDownloadFile(string ftpUrl, string username, string password, string remoteFile, string localFile)
{
    long offset = new FileInfo(localFile).Length;
    string url = $"{ftpUrl}/{remoteFile}";
    FtpWebRequest request = (FtpWebRequest)WebRequest.Create(url);
    request.Method = WebRequestMethods.Ftp.DownloadFile;
    request.Credentials = new NetworkCredential(username, password);
    request.ContentOffset = offset;
 
    using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
    using (Stream responseStream = response.GetResponseStream())
    using (FileStream fs = new FileStream(localFile, FileMode.Append))
    {
        responseStream.CopyTo(fs);
    }
}

3. 異常處理建議

try
{
    // FTP操作
}
catch (WebException ex)
{
    if (ex.Response is FtpWebResponse ftpResponse)
    {
        Console.WriteLine($"FTP響應: {ftpResponse.StatusDescription}");
    }
    else
    {
        Console.WriteLine($"網(wǎng)絡異常: {ex.Message}");
    }
}
catch (Exception ex)
{
    Console.WriteLine($"其他異常: {ex.Message}");
}

4. 推薦:使用 FluentFTP 第三方庫(更強大)

NuGet 安裝:

Install-Package FluentFTP

示例代碼:

using FluentFTP;
 
public void FluentFtpUpload(string host, string user, string pass, string localFile, string remoteFile)
{
    var client = new FtpClient(host, user, pass);
    client.Connect();
    client.UploadFile(localFile, remoteFile, FtpExists.Overwrite, true, FtpVerify.Retry);
    client.Disconnect();
}

FluentFTP 支持斷點續(xù)傳、批量操作、進度回調(diào)、SFTP等,API更現(xiàn)代,推薦生產(chǎn)環(huán)境使用。

5. 常見問題與建議

  • 推薦使用被動模式,防火墻友好:request.UsePassive = true;
  • FTP明文傳輸不安全,敏感業(yè)務建議用 SFTP/FTPS
  • 及時關閉連接和流,防止資源泄漏
  • 大文件建議分塊/斷點續(xù)傳,提升健壯性
  • 批量操作建議用多線程或異步(FluentFTP支持)

6. 批量上傳/下載(FluentFTP 推薦)

批量上傳

using FluentFTP;
 
public void BatchUpload(string host, string user, string pass, string localDir, string remoteDir)
{
    var client = new FtpClient(host, user, pass);
    client.Connect();
    foreach (var file in Directory.GetFiles(localDir))
    {
        client.UploadFile(file, $"{remoteDir}/{Path.GetFileName(file)}", FtpExists.Overwrite, true, FtpVerify.Retry);
    }
    client.Disconnect();
}

批量下載

public void BatchDownload(string host, string user, string pass, string remoteDir, string localDir)
{
    var client = new FtpClient(host, user, pass);
    client.Connect();
    foreach (var item in client.GetListing(remoteDir, FtpListOption.AllFiles))
    {
        if (item.Type == FtpFileSystemObjectType.File)
        {
            client.DownloadFile($"{localDir}\\{item.Name}", item.FullName, FtpLocalExists.Overwrite, FtpVerify.Retry);
        }
    }
    client.Disconnect();
}

7. 進度條與回調(diào)監(jiān)聽

FluentFTP 支持進度回調(diào),非常適合大文件或批量傳輸場景。

client.UploadFile(localFile, remoteFile, FtpExists.Overwrite, true, FtpVerify.None, progress: new Progress<FtpProgress>(p => {
    Console.WriteLine($"已上傳: {p.TransferredBytes}/{p.TotalBytes} ({p.Progress}% 完成)");
}));

8. 異步與多線程操作

FluentFTP 支持異步 API,可結(jié)合 async/await 實現(xiàn)高并發(fā):

public async Task AsyncUpload(string host, string user, string pass, string localFile, string remoteFile)
{
    var client = new FtpClient(host, user, pass);
    await client.ConnectAsync();
    await client.UploadFileAsync(localFile, remoteFile, FtpExists.Overwrite, true, FtpVerify.None);
    await client.DisconnectAsync();
}

多線程批量傳輸建議用 Parallel.ForEach 或 Task.Run,結(jié)合異步API。

9. SFTP 實現(xiàn)(推薦SSH.NET庫)

NuGet 安裝:

Install-Package SSH.NET

上傳/下載示例:

using Renci.SshNet;
 
public void SftpUpload(string host, string user, string pass, string localFile, string remoteFile)
{
    using (var sftp = new SftpClient(host, 22, user, pass))
    {
        sftp.Connect();
        using (var fs = new FileStream(localFile, FileMode.Open))
        {
            sftp.UploadFile(fs, remoteFile);
        }
        sftp.Disconnect();
    }
}
 
public void SftpDownload(string host, string user, string pass, string remoteFile, string localFile)
{
    using (var sftp = new SftpClient(host, 22, user, pass))
    {
        sftp.Connect();
        using (var fs = new FileStream(localFile, FileMode.Create))
        {
            sftp.DownloadFile(remoteFile, fs);
        }
        sftp.Disconnect();
    }
}

10. 健壯性與異常重試

int maxRetries = 3;
for (int i = 0; i < maxRetries; i++)
{
    try
    {
        // FTP/SFTP操作
        break;
    }
    catch (Exception ex)
    {
        Console.WriteLine($"重試 {i+1} 次: {ex.Message}");
        if (i == maxRetries - 1) throw;
        Thread.Sleep(1000);
    }
}

11. 遞歸上傳/下載目錄

FTP遞歸上傳(FluentFTP示例)

using FluentFTP;
 
public void UploadDirectoryRecursive(string host, string user, string pass, string localDir, string remoteDir)
{
    var client = new FtpClient(host, user, pass);
    client.Connect();
    client.UploadDirectory(localDir, remoteDir, FtpFolderSyncMode.Update, FtpRemoteExists.Overwrite, FtpVerify.None);
    client.Disconnect();
}

FTP遞歸下載

public void DownloadDirectoryRecursive(string host, string user, string pass, string remoteDir, string localDir)
{
    var client = new FtpClient(host, user, pass);
    client.Connect();
    client.DownloadDirectory(localDir, remoteDir, FtpFolderSyncMode.Update, FtpLocalExists.Overwrite, FtpVerify.None);
    client.Disconnect();
}

SFTP遞歸操作(SSH.NET)

using Renci.SshNet;
 
public void SftpDownloadDirectory(string host, string user, string pass, string remoteDir, string localDir)
{
    using (var sftp = new SftpClient(host, 22, user, pass))
    {
        sftp.Connect();
        var files = sftp.ListDirectory(remoteDir);
        Directory.CreateDirectory(localDir);
        foreach (var file in files)
        {
            if (!file.Name.StartsWith("."))
            {
                string localPath = Path.Combine(localDir, file.Name);
                string remotePath = file.FullName;
                if (file.IsDirectory)
                {
                    SftpDownloadDirectory(host, user, pass, remotePath, localPath);
                }
                else
                {
                    using (var fs = new FileStream(localPath, FileMode.Create))
                    {
                        sftp.DownloadFile(remotePath, fs);
                    }
                }
            }
        }
        sftp.Disconnect();
    }
}

12. 斷點續(xù)傳(FluentFTP示例)

client.UploadFile(localFile, remoteFile, FtpExists.Resume, false, FtpVerify.Retry);
client.DownloadFile(localFile, remoteFile, FtpLocalExists.Resume, FtpVerify.Retry);

Resume模式會自動檢測已上傳/下載的字節(jié)數(shù),斷點續(xù)傳。

13. 連接池設計建議

  • 對于高并發(fā)場景,建議用對象池(如自定義或結(jié)合 Microsoft.Extensions.ObjectPool)。
  • 每個線程/任務從池中借出連接,用完歸還,避免頻繁連接/斷開。
  • FluentFTP和SSH.NET都可自定義連接池(實現(xiàn) IDisposable,支持多線程)。

14. 跨平臺兼容性

  • .NET Core/6/7 支持 FluentFTP、SSH.NET,可在 Windows/Linux/Mac 部署。
  • 文件路徑注意區(qū)分 / 與 \,建議用 Path.Combine。
  • 字符編碼建議統(tǒng)一 UTF-8,避免中文亂碼。

15. 日志與監(jiān)控

  • FluentFTP支持事件監(jiān)聽,可記錄每次上傳/下載/異常。
  • 企業(yè)應用建議集成 Serilog/NLog/Log4Net 實現(xiàn)日志持久化與告警。
  • 可結(jié)合 Prometheus/Grafana 采集傳輸量、錯誤率等指標。

16. 安全加固建議

  • FTP傳輸建議啟用 FTPS(SSL/TLS),或優(yōu)先用 SFTP。
  • 密碼、主機等敏感信息用配置中心或環(huán)境變量管理,不要硬編碼。
  • 限制服務器端口、白名單IP,避免暴露在公網(wǎng)。
  • 定期更換賬號密碼,開啟服務器日志審計。

17. 企業(yè)應用架構(gòu)建議

  • 封裝 FTP/SFTP 工具類或服務,業(yè)務代碼只調(diào)用接口。
  • 支持批量任務、斷點續(xù)傳、自動重試、進度回調(diào)。
  • 結(jié)合定時任務/消息隊列,實現(xiàn)大文件/多文件異步傳輸。
  • 日志與監(jiān)控全鏈路覆蓋,保證可運維、可追溯。

18. 面試進階問題&答題思路

  1. 如何實現(xiàn)高可用的 FTP/SFTP 文件服務?

    • 多節(jié)點部署,連接池管理,自動重試,斷點續(xù)傳,監(jiān)控告警。
  2. FTP/SFTP在分布式系統(tǒng)中的應用場景?

    • 跨系統(tǒng)文件同步、定時批量數(shù)據(jù)交換、異地備份、與微服務/大數(shù)據(jù)平臺集成等。
  3. 如何應對大文件傳輸中的網(wǎng)絡抖動和中斷?

    • 斷點續(xù)傳、自動重連、分塊傳輸、錯誤重試、傳輸進度保存。
  4. 如何保證FTP/SFTP服務的安全性和合規(guī)性?

    • 使用加密協(xié)議(FTPS/SFTP)、權(quán)限細分、日志審計、配置白名單。
  5. C# FTP/SFTP與Java實現(xiàn)有何異同?

    • API不同,原理一致;C#推薦FluentFTP/SSH.NET,Java推薦Commons Net/JSch。

到此這篇關于C# FTP調(diào)用的實現(xiàn)示例的文章就介紹到這了,更多相關C# FTP調(diào)用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

您可能感興趣的文章:

相關文章

  • C# 調(diào)用WebApi的實現(xiàn)

    C# 調(diào)用WebApi的實現(xiàn)

    這篇文章主要介紹了C# 調(diào)用WebApi的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2021-04-04
  • WPF利用ScottPlot實現(xiàn)動態(tài)繪制圖像

    WPF利用ScottPlot實現(xiàn)動態(tài)繪制圖像

    ScottPlot是基于.Net的一款開源免費的交互式可視化庫,支持Winform和WPF等UI框架,本文主要為大家詳細介紹了如何WPF如何使用ScottPlot實現(xiàn)動態(tài)繪制圖像,需要的可以參考下
    2023-12-12
  • C#實現(xiàn)前向最大匹、字典樹(分詞、檢索)的示例代碼

    C#實現(xiàn)前向最大匹、字典樹(分詞、檢索)的示例代碼

    這篇文章主要介紹了C#實現(xiàn)前向最大匹、字典樹的示例代碼,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2020-05-05
  • C#程序最小化到托盤圖標操作步驟與實現(xiàn)代碼

    C#程序最小化到托盤圖標操作步驟與實現(xiàn)代碼

    設置窗體屬性showinTask=false;加notifyicon控件notifyIcon1,為控件notifyIcon1的屬性Icon添加一個icon圖標;添加窗體最小化事件(首先需要添加事件引用)接下來介紹實現(xiàn)代碼,感興趣的朋友可以研究下
    2012-12-12
  • C# Console.WriteLine()用法案例詳解

    C# Console.WriteLine()用法案例詳解

    這篇文章主要介紹了C# Console.WriteLine()用法案例詳解,本篇文章通過簡要的案例,講解了該項技術(shù)的了解與使用,以下就是詳細內(nèi)容,需要的朋友可以參考下
    2021-08-08
  • C# / VB.NET 在PPT中創(chuàng)建、編輯PPT SmartArt圖形的方法詳解

    C# / VB.NET 在PPT中創(chuàng)建、編輯PPT SmartArt圖形的方法詳解

    本文介紹通過C#和VB.NET程序代碼來創(chuàng)建和編輯PPT文檔中的SmartArt圖形。文中將分兩個操作示例來演示創(chuàng)建和編輯結(jié)果,需要的朋友可以參考下
    2020-10-10
  • C# 利用PdfSharp生成Pdf文件的示例

    C# 利用PdfSharp生成Pdf文件的示例

    這篇文章主要介紹了C# 利用PdfSharp生成Pdf文件的示例,幫助大家更好的理解和學習使用c#,感興趣的朋友可以了解下
    2021-04-04
  • C#中Activator.CreateInstance()方法用法分析

    C#中Activator.CreateInstance()方法用法分析

    這篇文章主要介紹了C#中Activator.CreateInstance()方法用法,實例分析了C#中Activator.CreateInstance()方法的功能、定義及使用技巧,需要的朋友可以參考下
    2015-03-03
  • WinForm項目中添加幫助文檔功能

    WinForm項目中添加幫助文檔功能

    這篇文章介紹了WinForm項目中添加幫助文檔功能的方法,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2022-06-06
  • C#?wpf使用DockPanel實現(xiàn)制作截屏框

    C#?wpf使用DockPanel實現(xiàn)制作截屏框

    做桌面客戶端的時候有時需要實現(xiàn)截屏功能,能夠在界面上框選截屏,本文就來為大家介紹一下wpf如何使用DockPanel制作截屏框吧,感興趣的可以了解下
    2023-09-09

最新評論

乌兰察布市| 胶州市| 宝鸡市| 阿拉善右旗| 梨树县| 寿阳县| 游戏| 农安县| 永和县| 凉山| 白银市| 佛坪县| 南溪县| 彰化市| 田阳县| 铁岭县| 宁河县| 栾城县| 洞口县| 师宗县| 沿河| 佛教| 平山县| 恭城| 阳新县| 贺州市| 全州县| 海门市| 呼伦贝尔市| 桐梓县| 同江市| 通化县| 泽普县| 蒙城县| 张家川| 大庆市| 新晃| 遂平县| 怀柔区| 邻水| 万全县|