FTP File Upload with HTTP Proxy

前端 未结 13 1960
轻奢々
轻奢々 2020-12-05 07:48

Is there a way to upload a file to a FTP server when behind an HTTP proxy ?

It seems that uploading a file is not supported behind an HTTP Proxy using .Net Webclient

13条回答
  •  半阙折子戏
    2020-12-05 08:23

    I'm not sure if all HTTP proxies work in the same way, but I managed to cheat ours by simply creating an HTTP request to access resource on URI ftp://user:pass@your.server.com/path.

    Sadly, to create an instance of HttpWebRequest you should use WebRequest.Create. And if you do that you can't create an HTTP request for ftp:// schema.

    So I used a bit of reflection to invoke a non-public constructor which does that:

    var ctor = typeof(HttpWebRequest).GetConstructor(
        BindingFlags.NonPublic | BindingFlags.Instance, 
        null, 
        new Type[] { typeof(Uri), typeof(ServicePoint) }, 
        null);
    var req = (WebRequest)ctor.Invoke(new object[] { new Uri("ftp://user:pass@host/test.txt"), null });
    req.Proxy = new WebProxy("myproxy", 8080);
    req.Method = WebRequestMethods.Http.Put;
    
    using (var inStream = req.GetRequestStream())
    {
        var buffer = Encoding.ASCII.GetBytes("test upload");
        inStream.Write(buffer, 0, buffer.Length);
    }
    
    using (req.GetResponse())
    {
    }
    

    You can also use other methods like "DELETE" for other tasks.

    In my case, it worked like a charm.

提交回复
热议问题