简体   繁体   English

将文件从Azure存储Blob移动到Ftp服务器

[英]Move files from Azure Storage blob to an Ftp server

I need to upload a few files from Azure Storage to an external Ftp server. 我需要将一些文件从Azure存储上载到外部Ftp服务器。

Is there any way with Azure to uplodad these files directly without download them before ? Azure是否可以直接升级这些文件而无需先下载它们?

You will need to use two classes/libraries and create two methods here: 您将需要使用两个类/库并在此处创建两个方法:

  1. WebClient class to download the file from the blob storage to your local drive WebClient类,用于将文件从Blob存储下载到本地驱动器
  2. FTP library such WinSCP to move the file FTP库,例如WinSCP来移动文件

WebClient Class: You need to supply the URI parameter with the format: https://[accountname].blob.core.windows.net/[containername]/[filetodownloadincludingextension] WebClient类:您需要提供URI参数,其格式为: https:// [accountname] .blob.core.windows.net / [containername] / [文件下载包括扩展名]

The download location must then be a variable as the origin location of the file to be uploaded to your FTP server. 然后,下载位置必须是一个变量,作为要上传到FTP服务器的文件的原始位置。

        string uri = "https://[accountname].blob.core.windows.net/[containername]/[filetodownloadincludingextension]/";
        string file = "file1.txt";
        string downloadLocation = @"C:\";

        WebClient webClient = new WebClient();
        Log("Downloading File from web...");
        try
        {
            webClient.DownloadFile(new Uri(uri+file), downloadLocation);
            Log("Download from web complete");
            webClient.Dispose();
        }
        catch (Exception ex)
        {
            Log("Error Occurred in downloading file. See below for exception details");
            Log(ex.Message);
            webClient.Dispose();
        } 
        return downloadLocation + file;

Once downloaded in your local drive, you need to upload it to your FTP/SFTP server. 下载到本地驱动器后,您需要将其上传到FTP / SFTP服务器。 You may use the library of WinSCP for this: 您可以为此使用WinSCP库:

        string absPathSource = downloadLocation + file;
        string destination = "/root/folder"; //this basically is your FTP path

    // Setup session options
        SessionOptions sessionOptions = new SessionOptions
        {

            Protocol = Protocol.Sftp,
            HostName = ConfigurationManager.AppSettings["scpurl"],
            UserName = ConfigurationManager.AppSettings["scpuser"],
            Password = ConfigurationManager.AppSettings["scppass"].Trim(),
            SshHostKeyFingerprint = ConfigurationManager.AppSettings["scprsa"].Trim()
        };

        using (Session session = new Session())
        {

            //disable version checking
            session.DisableVersionCheck = true;

            // Connect
            session.Open(sessionOptions);

            // Upload files
            TransferOptions transferOptions = new TransferOptions();
            transferOptions.TransferMode = TransferMode.Binary;

            TransferOperationResult transferResult;
            transferResult = session.PutFiles(absPathSource, destination, false, transferOptions);

            // Throw on any error
            transferResult.Check();

            // Print results
            foreach (TransferEventArgs transfer in transferResult.Transfers)
            {
                //Console.WriteLine("Upload of {0} succeeded", transfer.FileName);
            }
        }

You may include a File.Delete code at the end of the upload to FTP code if you want to delete the file from your local hard drive after the upload. 如果要在上传后从本地硬盘驱动器中删除文件,则可以在上传到FTP代码的末尾添加File.Delete代码。

I came across this question whilst looking for the same answer, I came up with the following solution: 我在寻找相同答案的同时遇到了这个问题,提出了以下解决方案:

  • Get the Azure file as a Stream [Handled by Azure Functions for you] 以流的形式获取Azure文件[由Azure函数为您处理]
  • Using WebClient Upload the Stream 使用WebClient上传流

This allowed me to transfer the file directly from Blob Storage to an FTP client. 这使我可以将文件直接从Blob存储传输到FTP客户端。 For me the Azure Blob file as a Stream was already done as I was creating an Azure Function based on a blob trigger. 对我而言,在基于blob触发器创建Azure函数时,已经完成了将Azure Blob文件作为流的操作。

I then converted the Stream to a MemoryStream and passed that to WebClient.UploadData() as a byte array [very roughly something like]: 然后,我将Stream转换为MemoryStream并将其作为字节数组传递给WebClient.UploadData()[非常相似]:

// ... Get the Azure Blob file in to a Stream called myBlob
// As mentioned above the Azure function does this for you:
// public static void Run([BlobTrigger("containerName/{name}", Connection = "BlobConnection")]Stream myBlob, string name, ILogger log)

public void UploadStreamToFtp(Stream file, string targetFilePath)
    {
        using (MemoryStream ms = new MemoryStream())
        {
            // As memory stream already handles ToArray() copy the Stream to the MemoryStream
            file.CopyTo(ms);

            using (WebClient client = new WebClient())
            {
                // Use login credentails if required
                client.Credentials = new NetworkCredential("username", "password");

                // Upload the stream as Data with the STOR method call
                // targetFilePath is a fully qualified filepath on the FTP, e.g. ftp://targetserver/directory/filename.ext
                client.UploadData(targetFilePath, WebRequestMethods.Ftp.UploadFile, ms.ToArray());
            }
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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