FTP工具FileZilla、WinSCP、FTP類庫FluentFTP


一、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);
            }
        }
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM