【问题标题】:using WebClient getting unable to connect to remote server使用 WebClient 无法连接到远程服务器
【发布时间】:2019-04-15 12:48:38
【问题描述】:

我已经尝试了以下我能想到的所有变体。

client.Credentials = new NetworkCredential(ftpInfo.ftpUserName, ftpInfo.ftpPassWord);
client.BaseAddress = "ftp://99.999.9.99";
var response = client.UploadFile("testFile.txt", "C:\\ftproot\\testfile\\012\\Drop\\testFile.txt");

我知道用户名和密码是正确的。 如果我从同一个盒子中使用 filezilla 连接到服务器,它就可以工作。

我尝试过不使用 ftp:// ——我必须遗漏一些非常简单的东西。

这是错误: {"无法连接到远程服务器"}

  • 响应 {System.Net.FtpWebResponse} System.Net.WebResponse {System.Net.FtpWebResponse}
  • ContentType '($exception).Response.ContentType' 引发了类型为 'System.NotImplementedException' 字符串 {System.NotImplementedException} 的异常

更新: 我不知道这个问题有什么问题。我已经提供了尽可能多的信息。

这是使用注释中的一些建议进行的当前测试。

using (WebClient client = new WebClient())
{
    client.Credentials = new NetworkCredential("password", "loginname");
    client.UploadFile("ftp://99.999.6.130/testFile.txt", "STOR", "c:\\testfile.txt");
} 

这只是说明我没有登录。

下面的工作....我会在允许的时候结束这个问题。

最终更新——可行的解决方案:

public static bool UploadFile(string url, string userName, string password, string file, out string statusDescription)
{
    try
    {
        var request = (FtpWebRequest)WebRequest.Create(url);
        request.Method = WebRequestMethods.Ftp.UploadFile;

        request.Credentials = new NetworkCredential(userName, password);

        // Copy the entire contents of the file to the request stream.
        var sourceStream = new StreamReader(file);
        var fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
        sourceStream.Close();
        request.ContentLength = fileContents.Length;
        var getResponse = request.GetResponse();

        Console.WriteLine($"{fileContents.Length} {getResponse} ");
    }
}

【问题讨论】:

  • 下载文件有用吗?
  • 可以是任意数量的东西。代理可能吗?
  • 尝试使用 WebRequestMethods.Ftp.UploadFile 作为第二个参数
  • @CodeNameJack 为什么? UploadFile根据URL选择正确的方法
  • 您是否收到错误消息?超时?是不是上传太慢了?如果遇到错误或异常,Exception.ToString() 返回的 full 异常文本是什么?

标签: c# ftp


【解决方案1】:

以下是一个可行的解决方案。

public static bool UploadFile(string url, string userName, string password, string file, out string statusDescription)
{
    try
    {
        var request = (FtpWebRequest)WebRequest.Create(url);
        request.Method = WebRequestMethods.Ftp.UploadFile;

        request.Credentials = new NetworkCredential(userName, password);

        // Copy the entire contents of the file to the request stream.
        var sourceStream = new StreamReader(file);
        var fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
        sourceStream.Close();
        request.ContentLength = fileContents.Length;
        var getResponse = request.GetResponse();

        Console.WriteLine($"{fileContents.Length} {getResponse} ");
    }
}

【讨论】:

  • 这不是问题的答案。这基本上是WebClient 在内部所做的。如果这有效,那么WebClient 也必须有效。你一定是给它传递了错误的参数。
  • 这很有趣....我会回到我的原始代码,看看我可能错过了什么。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多