文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

C#调用第三方工具完成FTP操作

2024-04-02 19:55

关注

一、FileZilla

Filezilla分为client和server。其中FileZilla Server是Windows平台下一个小巧的第三方FTP服务器软件,系统资源也占用非常小,可以让你快速简单的建立自己的FTP服务器。

打开FileZilla,进行如下操作

下图红色区域就是linux系统的文件目录,可以直接把windows下的文件直接拖拽进去。

二、WinSCP

跟FileZilla一样,也是一款十分方便的文件传输工具。WinSCP是连接Windows和Linux的。

WinSCP .NET Assembly and SFTP

https://winscp.net/eng/docs/library#csharp

// Setup session options
SessionOptions sessionOptions = new SessionOptions
{
    Protocol = Protocol.Sftp,
    HostName = "example.com",
    UserName = "user",
    Password = "mypassword",
    SshHostKeyFingerprint = "ssh-rsa 2048 xxxxxxxxxxx...="
};

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

    // Upload files
    TransferOptions transferOptions = new TransferOptions();
    transferOptions.TransferMode = TransferMode.Binary;

    TransferOperationResult transferResult;
    transferResult =  session.PutFiles(@"d:\toupload\*", "/home/user/", false, transferOptions);

    // Throw on any error
    transferResult.Check();

    // Print results
    foreach (TransferEventArgs transfer in transferResult.Transfers)
    {
        Console.WriteLine("Upload of {0} succeeded", transfer.FileName);
    }
}

三、FluentFTP

FluentFTP是一款老外开发的基于.Net的支持FTP及的FTPS 的FTP类库,FluentFTP是完全托管的FTP客户端,被设计为易于使用和易于扩展。它支持文件和目录列表,上传和下载文件和SSL / TLS连接。

它底层由Socket实现,可以连接到Unix和Windows IIS建立FTP的服务器,

github:https://github.com/robinrodricks/FluentFTP

举例:

// create an FTP client
FtpClient client = new FtpClient("123.123.123.123");

// if you don't specify login credentials, we use the "anonymous" user account
client.Credentials = new NetworkCredential("david", "pass123");

// begin connecting to the server
client.Connect();

// get a list of files and directories in the "/htdocs" folder
foreach (FtpListItem item in client.GetListing("/htdocs")) {
    
    // if this is a file
    if (item.Type == FtpFileSystemObjectType.File){
        
        // get the file size
        long size = client.GetFileSize(item.FullName);
        
    }
    
    // get modified date/time of the file or folder
    DateTime time = client.GetModifiedTime(item.FullName);
    
    // calculate a hash for the file on the server side (default algorithm)
    FtpHash hash = client.GetHash(item.FullName);
    
}

// upload a file
client.UploadFile(@"C:\MyVideo.mp4", "/htdocs/big.txt");

// rename the uploaded file
client.Rename("/htdocs/big.txt", "/htdocs/big2.txt");

// download the file again
client.DownloadFile(@"C:\MyVideo_2.mp4", "/htdocs/big2.txt");

// delete the file
client.DeleteFile("/htdocs/big2.txt");

// delete a folder recursively
client.DeleteDirectory("/htdocs/extras/");

// check if a file exists
if (client.FileExists("/htdocs/big2.txt")){ }

// check if a folder exists
if (client.DirectoryExists("/htdocs/extras/")){ }

// upload a file and retry 3 times before giving up
client.RetryAttempts = 3;
client.UploadFile(@"C:\MyVideo.mp4", "/htdocs/big.txt", FtpExists.Overwrite, false, FtpVerify.Retry);

// disconnect! good bye!
client.Disconnect();

对FluentFTP部分操作封装类

public class FtpFileMetadata
{
    public long FileLength { get; set; }
    public string MD5Hash { get; set; }
    public DateTime LastModifyTime { get; set; }
}

public class FtpHelper
{
    private FtpClient _client = null;
    private string _host = "127.0.0.1";
    private int _port = 21;
    private string _username = "Anonymous";
    private string _password = "";
    private string _workingDirectory = "";
    public string WorkingDirectory
    {
        get
        {
            return _workingDirectory;
        }
    }
    public FtpHelper(string host, int port, string username, string password)
    {
        _host = host;
        _port = port;
        _username = username;
        _password = password;
    }

    public Stream GetStream(string remotePath)
    {
        Open();
        return _client.OpenRead(remotePath);
    }

    public void Get(string localPath, string remotePath)
    {
        Open();
        _client.DownloadFile(localPath, remotePath, true);
    }

    public void Upload(Stream s, string remotePath)
    {
        Open();
        _client.Upload(s, remotePath, FtpExists.Overwrite, true);
    }

    public void Upload(string localFile, string remotePath)
    {
        Open();
        using (FileStream fileStream = new FileStream(localFile, FileMode.Open))
        {
            _client.Upload(fileStream, remotePath, FtpExists.Overwrite, true);
        }
    }

    public int UploadFiles(IEnumerable<string> localFiles, string remoteDir)
    {
        Open();
        List<FileInfo> files = new List<FileInfo>();
        foreach (var lf in localFiles)
        {
            files.Add(new FileInfo(lf));
        }
        int count = _client.UploadFiles(files, remoteDir, FtpExists.Overwrite, true, FtpVerify.Retry);
        return count;
    }

    public void MkDir(string dirName)
    {
        Open();
        _client.CreateDirectory(dirName);
    }

    public bool FileExists(string remotePath)
    {
        Open();
        return _client.FileExists(remotePath);
    }
    public bool DirExists(string remoteDir)
    {
        Open();
        return _client.DirectoryExists(remoteDir);
    }

    public FtpListItem[] List(string remoteDir)
    {
        Open();
        var f = _client.GetListing();
        FtpListItem[] listItems = _client.GetListing(remoteDir);
        return listItems;
    }

    public FtpFileMetadata Metadata(string remotePath)
    {
        Open();
        long size = _client.GetFileSize(remotePath);
        DateTime lastModifyTime = _client.GetModifiedTime(remotePath);

        return new FtpFileMetadata()
        {
            FileLength = size,
            LastModifyTime = lastModifyTime
        };
    }

    public bool TestConnection()
    {
        return _client.IsConnected;
    }

    public void SetWorkingDirectory(string remoteBaseDir)
    {
        Open();
        if (!DirExists(remoteBaseDir))
            MkDir(remoteBaseDir);
        _client.SetWorkingDirectory(remoteBaseDir);
        _workingDirectory = remoteBaseDir;
    }
    private void Open()
    {
        if (_client == null)
        {
            _client = new FtpClient(_host, new System.Net.NetworkCredential(_username, _password));
            _client.Port = 21;
            _client.RetryAttempts = 3;
            if (!string.IsNullOrWhiteSpace(_workingDirectory))
            {
                _client.SetWorkingDirectory(_workingDirectory);
            }
        }
    }
}

到此这篇关于C#调用第三方工具完成FTP操作的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持编程网。

阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     813人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     354人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     318人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     435人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     224人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-后端开发
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯