将文件直接从 FTP 传输到 Azure 文件存储,无需将它们保存在本地内存或磁盘中

2024-03-11

我必须将文件从 FTP 传输到 Azure 文件存储。我的代码工作正常,但我正在内存中传输这些文件,这不是最佳实践。所以首先我将流读取到Byte内存中的数组。然后我将输出上传到 Azure 文件存储。

现在我知道最好异步执行此操作。但我不知道这是否可能以及如何做到。

My code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.WindowsAzure.Storage;
using System.Configuration;
using Microsoft.WindowsAzure.Storage.File;
using System.IO;
using Microsoft.Azure;
using System.Net;

namespace TransferFtpToAzure
{
    class Program
    {
        public static void Main(string[] args)
        {
            List<FileName> sourceFileList = new List<FileName>();
            List<FileName> targetFileList = new List<FileName>();

            string targetShareReference = ConfigurationManager.AppSettings["AzureShare"];
            string targetDirectoryReference = ConfigurationManager.AppSettings["Environment"] + "/" + Enums.AzureFolders.Mos + "/" + Enums.AzureFolders.In;
            string sourceURI = (ConfigurationManager.AppSettings["FtpConnectionString"] + ConfigurationManager.AppSettings["Environment"].ToUpper() +"/"+ Enums.FtpFolders.Mos + "/").Replace("\\","/");
            string sourceUser = ConfigurationManager.AppSettings["FtpServerUserName"];
            string sourcePass = ConfigurationManager.AppSettings["FtpServerPassword"];

            getFileLists(sourceURI, sourceUser, sourcePass, sourceFileList, targetShareReference, targetDirectoryReference, targetFileList);

            Console.WriteLine(sourceFileList.Count + " files found!");

            CheckLists(sourceFileList, targetFileList);
            targetFileList.Sort();

            Console.WriteLine(sourceFileList.Count + " unique files on sourceURI" + Environment.NewLine + "Attempting to move them.");

            foreach (var file in sourceFileList)
            {
                try
                {
                    CopyFile(file.fName, sourceURI, sourceUser, sourcePass, targetShareReference, targetDirectoryReference);
                }
                catch
                {
                    Console.WriteLine("There was move error with : " + file.fName);
                }
            }
        }

        public class FileName : IComparable<FileName>
        {
            public string fName { get; set; }
            public int CompareTo(FileName other)
            {
                return fName.CompareTo(other.fName);
            }
        }

        public static void CheckLists(List<FileName> sourceFileList, List<FileName> targetFileList)
        {
            for (int i = 0; i < sourceFileList.Count; i++)
            {
                if (targetFileList.BinarySearch(sourceFileList[i]) > 0)
                {
                    sourceFileList.RemoveAt(i);
                    i--;
                }
            }
        }

        public static void getFileLists(string sourceURI, string sourceUser, string sourcePass, List<FileName> sourceFileList, string targetShareReference, string targetDirectoryReference, List<FileName> targetFileList)
        {
            string line = "";
            /////////Source FileList
            FtpWebRequest sourceRequest;
            sourceRequest = (FtpWebRequest)WebRequest.Create(sourceURI);
            sourceRequest.Credentials = new NetworkCredential(sourceUser, sourcePass);
            sourceRequest.Method = WebRequestMethods.Ftp.ListDirectory;
            sourceRequest.UseBinary = true;
            sourceRequest.KeepAlive = false;
            sourceRequest.Timeout = -1;
            sourceRequest.UsePassive = true;
            FtpWebResponse sourceRespone = (FtpWebResponse)sourceRequest.GetResponse();
            //Creates a list(fileList) of the file names
            using (Stream responseStream = sourceRespone.GetResponseStream())
            {
                using (StreamReader reader = new StreamReader(responseStream))
                {
                    line = reader.ReadLine();
                    while (line != null)
                    {
                        var fileName = new FileName
                        {
                            fName = line
                        };
                        sourceFileList.Add(fileName);
                        line = reader.ReadLine();
                    }
                }
            }
            /////////////Target FileList
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString"));
            CloudFileClient fileClient = storageAccount.CreateCloudFileClient();
            //var test = fileClient.ListShares();
            CloudFileShare fileShare = fileClient.GetShareReference(targetShareReference);
            if (fileShare.Exists())
            {
                CloudFileDirectory rootDirectory = fileShare.GetRootDirectoryReference();
                if (rootDirectory.Exists())
                {
                    CloudFileDirectory customDirectory = rootDirectory.GetDirectoryReference(targetDirectoryReference);
                    if (customDirectory.Exists())
                    {
                        var fileCollection = customDirectory.ListFilesAndDirectories().OfType<CloudFile>();
                        foreach (var item in fileCollection)
                        {
                            var fileName = new FileName
                            {
                                fName = item.Name
                            };
                            targetFileList.Add(fileName);
                        }
                    }
                }
            }
        }

        public static void CopyFile(string fileName, string sourceURI, string sourceUser, string sourcePass, string targetShareReference, string targetDirectoryReference)
        {
            try
            {
                FtpWebRequest request = (FtpWebRequest)WebRequest.Create(sourceURI + fileName);
                request.Method = WebRequestMethods.Ftp.DownloadFile;
                request.Credentials = new NetworkCredential(sourceUser, sourcePass);
                FtpWebResponse response = (FtpWebResponse)request.GetResponse();
                Stream responseStream = response.GetResponseStream();
                Upload(fileName, ToByteArray(responseStream), targetShareReference, targetDirectoryReference);
                responseStream.Close();
            }
            catch
            {
                Console.WriteLine("There was an error with :" + fileName);
            }
        }

        public static Byte[] ToByteArray(Stream stream)
        {
            MemoryStream ms = new MemoryStream();
            byte[] chunk = new byte[4096];
            int bytesRead;
            while ((bytesRead = stream.Read(chunk, 0, chunk.Length)) > 0)
            {
                ms.Write(chunk, 0, bytesRead);
            }

            return ms.ToArray();
        }

        public static bool Upload(string FileName, byte[] Image, string targetShareReference, string targetDirectoryReference)
        {
            try
            {
                CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString"));
                CloudFileClient fileClient = storageAccount.CreateCloudFileClient();
                //var test = fileClient.ListShares();
                CloudFileShare fileShare = fileClient.GetShareReference(targetShareReference);
                if (fileShare.Exists())
                {
                    CloudFileDirectory rootDirectory = fileShare.GetRootDirectoryReference();
                    if (rootDirectory.Exists())
                    {
                        CloudFileDirectory customDirectory = rootDirectory.GetDirectoryReference(targetDirectoryReference);
                        if (customDirectory.Exists())
                        {
                            var cloudFile = customDirectory.GetFileReference(FileName);
                            using (var stream = new MemoryStream(Image, writable: false))
                            {
                                cloudFile.UploadFromStream(stream);
                            }
                        }
                    }
                }
                return true;
            }
            catch
            {
                return false;
            }
        }
    }
}

如果我理解正确,您希望避免在下载和上传之间将文件存储在内存中。

为此,请参阅:
将文件从 FTP 复制到 Blob 存储的 Azure 函数 https://stackoverflow.com/q/56847967/850848#56848773.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将文件直接从 FTP 传输到 Azure 文件存储,无需将它们保存在本地内存或磁盘中 的相关文章

随机推荐

  • 如何检测 GHC 默认生成 32 位还是 64 位代码?

    我的里面有以下内容makefile https github com bsl GLFW b blob master Makefile GLFW FLAG m32 O2 Iglfw include Iglfw lib Iglfw lib co
  • jwt 令牌过期后如何注销

    我正在开发一个网络应用程序 使用node js and vue js 我正在使用进行身份验证和维护会话jwt and passport js using passport jwtstrategy 我已经完成了从创建 jwt 到保护路由的所有
  • 如何在 Python 中对编辑距离超过 80% 的单词进行分组

    假设我有一个清单 person name zakesh oldman LLC bikash goldman LLC zikash rakesh 我正在尝试以这种方式对列表进行分组 以便编辑距离 https en wikipedia org
  • 在远程计算机上运行命令

    我想使用 C 在远程计算机上的命令提示符中运行命令 根据此链接如何在远程计算机上执行命令 https stackoverflow com questions 428276 how to execute a command in a remo
  • 我需要调用[super viewDidUnload]吗?

    我见过一些Apple调用的例子 super viewDidUnload 也有一些没有 我读过一篇文章 几个月前所以我不记得网址 说打电话 super viewDidUnload 是不必要的 但除此之外没有解释 是否有明确的理由为什么或为什么
  • 分段错误 p_thread 可能存在竞争条件

    问题 我创建了子线程 TIDS 的链接列表 并希望在继续主线程之前等待所有子线程 TIDS 完成执行 基本上我有目录遍历 目录由给定的成员指定struct 每次我看到一个目录或文件时 我都会创建一个新线程并将其放入threadID进入链表
  • 通过逻辑索引为数组赋值不起作用

    在Matlab中 我想用其他值替换某个值 我知道我可以这样做 X X 0 1 如果我想将所有出现的 0 替换为 1 我有一个数组 X 其中包含范围在 0 到 9 之间的数字 我想创建一个新数组 Y 其中如果 X i 某个给定数字 例如 5
  • 将列表附加到 R 中的列表列表

    我在将数据附加到已经采用列表格式的列表时遇到问题 我有一个程序 它将在模拟循环期间导出结果对象 数据本身存储为矩阵列表 我的想法是将这些列表存储在一个列表中 然后将此列表列表保存为 R 对象以供以后分析 但是我在正确实现这一点时遇到了一些问
  • 如何在 git checkout 中使用八进制字符?

    我有一个音乐文件的 git 存储库 最近我发现有些文件被删除了 我想我不小心删除了它们 但现在我只是短暂地陶醉于我有先见之明的事实 使用 git 存储库 因此我当前的 git 状态验证它们已被删除 以下是一些清单 deleted Steve
  • 在 ASP .NET (SMTP) 中发送邮件

    我在代码文件中编写了以下代码 但它不起作用 请帮助我 protected void Button1 Click object sender EventArgs e MailMessage msgeme new MailMessage ema
  • VBA:复制时前面的零被删除

    我正在使用 VBA 创建 Excel 文件的副本 在该文件中 有一列包含前面带有零的数字 该文件的副本已创建 但该列中的数据将被删除 我需要保留前面带有零的值 我该如何用VBA解决这个问题 最好的方法是通过将 Range NumberFor
  • 带有泛型的映射数组的问题[重复]

    这个问题在这里已经有答案了 可能的重复 Java 泛型和数组初始化 https stackoverflow com questions 470198 java generics and array initialization 如何在 Ja
  • 代码在 g++ 中运行完美,但在 Xcode 中则不然 - 找不到文件

    我创建了一个包含内容的文本文件 它与 cpp 文件位于同一文件夹中 而且我已经多次确认该文件存在 当我运行 g 时 编译并运行它会找到该文件 当我在 Xcode 中运行它时 它不起作用 如果找不到该文件 include
  • int 和 NSInteger 有什么区别? [复制]

    这个问题在这里已经有答案了 可能的重复 何时使用 NSInteger 与 int https stackoverflow com questions 4445173 when to use nsinteger vs int 为什么会有 NS
  • 检查 .lib 文件的工具?

    我正在评估一些文档不足的软件 当我构建示例项目时 我收到一个链接器错误 如下所示 error LNK2019 unresolved external symbol 这个应用程序没有大量的 lib 文件 因此我可以通过反复试验来解决这个问题
  • 嵌入式非托管 DLL 无法在 ASP.NET 中加载

    我正在为 WCF 服务开发 ASP NET 主机 该服务引用 C CLI 包装器库 该库本身引用非托管 DLL 基于这个问题 https stackoverflow com questions 2907169 asp net load un
  • 亚音速 3.0.0.3 崩溃

    运行最新版本的 SubSonic 3 0 0 3 检索单个记录 更改一个字段并调用 Save 会导致以下代码中出现空引用异常 公共无效更新 IDataProvider提供者 if this dirtyColumns Count gt 0 r
  • 如何处理 next.js 路由中的尾部斜杠?

    我正在尝试设置 next js 应用程序 但在处理带有尾部斜杠的路由时遇到问题 因此 例如 如果我有这样的页面结构 pages index js blog index js slug js 然后去 给我基础index js 即将 blog给
  • msdeploy 上的嵌套虚拟目录已删除

    我的项目使用 msdeploy 将包发布到 IIS 它部署在项目的现有版本上 在Web应用程序中 我有一个虚拟目录 但每次部署项目时 虚拟目录都会消失 我通过以下方式调用 MSDepoly source package d 9 1 0 67
  • 将文件直接从 FTP 传输到 Azure 文件存储,无需将它们保存在本地内存或磁盘中

    我必须将文件从 FTP 传输到 Azure 文件存储 我的代码工作正常 但我正在内存中传输这些文件 这不是最佳实践 所以首先我将流读取到Byte内存中的数组 然后我将输出上传到 Azure 文件存储 现在我知道最好异步执行此操作 但我不知道