将文件从 FTP 复制到 Azure Blob 存储

时间:2021-01-06 03:09:04

标签: azure ftp azure-web-app-service blob

我已经使用用户 ID 和凭据创建了我的 FTP (ftp://xyz.in)。 我创建了一个 asp.net 核心 API 应用程序,它将文件从 FTP 复制到 Azure blob 存储。 我将我的 API 解决方案放在 C://Test2/Test2 文件夹中。 现在下面是我的代码:

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

但是在线 使用 (StreamReader sourceStream = new StreamReader("ftp://xyz.in/abc.txt"))
我收到错误:System.IO.IOException:'文件名、目录名或卷标语法不正确:'C:\Test2\Test2\ftp:\xyz.in\abc.txt''

我无法理解 'C:\Test2\Test2' 字符串从哪里附加到我的 FTP。 Test2 是放置我的 .Net Core 应用程序的文件夹。

1 个答案:

答案 0 :(得分:0)

StreamReader() 不采用 URL/URI,它采用本地系统上的文件路径:(阅读 doco): https://docs.microsoft.com/en-us/dotnet/api/system.io.streamreader.-ctor?view=net-5.0

StreamReader 正在插入您作为文件名提供的字符串(“ftp://xyz.in/abc.txt”),并且它正在当前运行的文件夹“C:\Test2\Test2”中寻找它。如果您的字符串是“abc.txt”,它会在当前文件夹中查找名为“abc.txt”的文件,例如C:\Test2\Test2\abc.txt。

您想要的是使用 WebClient 或类似方法获取文件:

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...
}