简体   繁体   中英

Copying files from FTP to Azure Blob Storage

I have created my FTP ( ftp://xyz.in ) with user id and credentials. I have created an asp.net core API application that will copy files from FTP to Azure blob storage.I have my API solution placed in C://Test2/Test2 folder. Now below is my code:

        FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp:/xyz.in");
        request.Method = WebRequestMethods.Ftp.UploadFile;

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

        // Copy the contents of the file to the request stream.
        byte[] fileContents;
        // Getting error in below line.
        using (StreamReader sourceStream = new StreamReader("ftp://xyz.in/abc.txt")) 

        {
                fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
        }

        request.ContentLength = fileContents.Length;

        using (Stream requestStream = request.GetRequestStream())
        {
            requestStream.Write(fileContents, 0, fileContents.Length);
        }

        using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
        {
            Console.WriteLine($"Upload File Complete, status {response.StatusDescription}");
        }

But on line using (StreamReader sourceStream = new StreamReader("ftp://xyz.in/abc.txt"))
I am getting error: System.IO.IOException: 'The filename, directory name, or volume label syntax is incorrect: 'C:\Test2\Test2\ftp:\xyz.in\abc.txt''

I am not able to understand from where does 'C:\Test2\Test2' string gets append to my FTP. Test2 is a folder where my.Net Core application is placed.

StreamReader() doesn't take a URL/URI, it takes a file path on your local system: (read the doco): https://docs.microsoft.com/en-us/dotnet/api/system.io.streamreader.-ctor?view=net-5.0

StreamReader is interpurting the string you've supplied as a filename ("ftp://xyz.in/abc.txt"), and it's looking for it in the current running folder "C:\Test2\Test2". If your string was "abc.txt", it would look for a file called "abc.txt" in the current folder, eg C:\Test2\Test2\abc.txt.

What you want is to get the file using WebClient or something similar:

WebClient request = new WebClient();
string url = "ftp://xyz.in/abc.txt";
request.Credentials = new NetworkCredential("username", "password");

try
{
  byte[] fileContents = request.DownloadData(url);

  // Do Something...
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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