使用C#连接到FTP服务器

时间:2020-06-29 16:57:04

标签: c# ftp

尝试使用端口连接到FTP服务器,以查看其是否正常工作。

如果使用端口21,我将收到错误消息:530未登录;如果使用端口22,则我将收到错误消息,表明服务器违反了协议。

我确定我的防火墙已关闭,是否还有其他要检查的内容或我的代码错误?

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());
}

1 个答案:

答案 0 :(得分:0)

我能够使用Fluent FTP库上传文件,这使我的生活更加轻松。 下面是我使用的代码示例。

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