简体   繁体   English

连接到 C# 中的 FTP 服务器

[英]Connect to FTP server in C#

Trying to connect to an FTP server using a port just to see if it work.尝试使用端口连接到 FTP 服务器只是为了查看它是否工作。

If I use port 21 I get an error: 530 Not logged in and if I use port 22 I get an error the server committed a protocol violation.如果我使用端口 21,我会收到一个错误:530 未登录,如果我使用端口 22,我会收到一个错误,服务器违反了协议。

I made sure my firewall is off, is there anything else to check or my code is wrong?我确保我的防火墙已关闭,是否还有其他需要检查的内容或我的代码有误?

try
{
    FtpWebRequest directoryListRequest = (FtpWebRequest)WebRequest.Create("ftp://ftp.fakeURL.com:22/");
    directoryListRequest.Method = WebRequestMethods.Ftp.ListDirectory;
    directoryListRequest.Credentials = new NetworkCredential("username", "password");

    using (FtpWebResponse directoryListResponse = (FtpWebResponse)directoryListRequest.GetResponse())
    {
        using (StreamReader directoryListResponseReader = new StreamReader(directoryListResponse.GetResponseStream()))
        {
            string responseString = directoryListResponseReader.ReadToEnd();
            string[] results = responseString.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries);
        }
    }
}
catch (Exception ex)
{
    Console.WriteLine(ex.Message.ToString());
}

I was able to use Fluent FTP library to upload the file and it made my life way easier.我能够使用 Fluent FTP 库来上传文件,这让我的生活变得更轻松。 below an example of the code I used.下面是我使用的代码示例。

public static async Task UploadFileAsync() {
    var token = new CancellationToken();
    using (var ftp = new FtpClient("127.0.0.1", "ftptest", "ftptest")) {
        await ftp.ConnectAsync(token);

        // upload a file to an existing FTP directory
        await ftp.UploadFileAsync(@"D:\Github\FluentFTP\README.md", "/public_html/temp/README.md");

        // upload a file and ensure the FTP directory is created on the server
        await ftp.UploadFileAsync(@"D:\Github\FluentFTP\README.md", "/public_html/temp/README.md", FtpRemoteExists.Overwrite, true);

        // upload a file and ensure the FTP directory is created on the server, verify the file after upload
        await ftp.UploadFileAsync(@"D:\Github\FluentFTP\README.md", "/public_html/temp/README.md", FtpRemoteExists.Overwrite, true, FtpVerify.Retry);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM