C# Ftp Upload in Windows 10 Universal app?

2019-02-28 06:14发布

问题:

I want to upload files from windows 10 app using ftp, I tried the following code.

    using System;
    using System.IO;
    using System.Net;
    using System.Text;

    namespace Examples.System.Net
    {
        public class WebRequestGetExample
        {
            public static void Main ()
            {
        // Get the object used to communicate with the server.
                FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://www.contoso.com/test.htm");
        request.Method = WebRequestMethods.Ftp.UploadFile;

        // This example assumes the FTP site uses anonymous logon.
        request.Credentials = new NetworkCredential ("anonymous","janeDoe@contoso.com");

        // Copy the contents of the file to the request stream.
        StreamReader sourceStream = new StreamReader("testfile.txt");
        byte [] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
        sourceStream.Close();
        request.ContentLength = fileContents.Length;

        Stream requestStream = request.GetRequestStream();
        requestStream.Write(fileContents, 0, fileContents.Length);
        requestStream.Close();

        FtpWebResponse response = (FtpWebResponse)request.GetResponse();

        Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription);

        response.Close();
        }
    }
        }
    }

But visual studio couldn't find the name space FtpWebRequest or WebRequestMethods. The other method i tried using backgroundtransfer api's from link but it says that WinRT information: 'uri': Uploading content is only supported for 'http' and 'https' schemes. not ftp.

So is there any solution to this where i can show progress bar and speed?

回答1:

The FtpWebRequest class is not part of the store profile for UWP apps, and FTP upload (as you determined) is not supported via the BackgroundTransfer API. This leave you with implementing your own FTP protocol over sockets. See FTP Endeavor in WinRT for an explanation and a link to a sample.



回答2:

Try this: https://github.com/kiewic/FtpClient

If you cannot open the project (e. g. with VS 2017), just take the two relevant classes from it.