如何将对象传输到 Azure Blob 存储而不将文件保存在本地存储上?

2024-04-05

我一直在关注这个来自 GitHub 的示例 https://github.com/Azure-Samples/storage-blobs-dotnet-quickstart将文件传输到 Azure Blob 存储。程序在本地创建一个文件MyDocuments要上传到 blob 容器的文件夹。创建文件后,会将其上传到容器。是否可以在内存中创建 JSON 对象并将其发送到 Azure Blob 存储,而无需先将该文件写入硬盘?

namespace storage_blobs_dotnet_quickstart
{
    using Microsoft.Azure.Storage;
    using Microsoft.Azure.Storage.Blob;
    using System;
    using System.IO;
    using System.Threading.Tasks;

    public static class Program
    {
        public static void Main()
        {
            Console.WriteLine("Azure Blob Storage - .NET quickstart sample");
            Console.WriteLine();
            ProcessAsync().GetAwaiter().GetResult();

            Console.WriteLine("Press any key to exit the sample application.");
            Console.ReadLine();
        }

        private static async Task ProcessAsync()
        {
            CloudStorageAccount storageAccount = null;
            CloudBlobContainer cloudBlobContainer = null;
            string sourceFile = null;
            string destinationFile = null;

            // Retrieve the connection string for use with the application. The storage connection string is stored
            // in an environment variable on the machine running the application called storageconnectionstring.
            // If the environment variable is created after the application is launched in a console or with Visual
            // Studio, the shell needs to be closed and reloaded to take the environment variable into account.
            string storageConnectionString = Environment.GetEnvironmentVariable("storageconnectionstring");

            // Check whether the connection string can be parsed.
            if (CloudStorageAccount.TryParse(storageConnectionString, out storageAccount))
            {
                try
                {
                    // Create the CloudBlobClient that represents the Blob storage endpoint for the storage account.
                    CloudBlobClient cloudBlobClient = storageAccount.CreateCloudBlobClient();

                    // Create a container called 'quickstartblobs' and append a GUID value to it to make the name unique. 
                    cloudBlobContainer = cloudBlobClient.GetContainerReference("quickstartblobs" + Guid.NewGuid().ToString());
                    await cloudBlobContainer.CreateAsync();
                    Console.WriteLine("Created container '{0}'", cloudBlobContainer.Name);
                    Console.WriteLine();

                    // Set the permissions so the blobs are public. 
                    BlobContainerPermissions permissions = new BlobContainerPermissions
                    {
                        PublicAccess = BlobContainerPublicAccessType.Blob
                    };
                    await cloudBlobContainer.SetPermissionsAsync(permissions);

                    // Create a file in your local MyDocuments folder to upload to a blob.
                    string localPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                    string localFileName = "QuickStart_" + Guid.NewGuid().ToString() + ".txt";
                    sourceFile = Path.Combine(localPath, localFileName);
                    // Write text to the file.
                    File.WriteAllText(sourceFile, "Hello, World!");

                    Console.WriteLine("Temp file = {0}", sourceFile);
                    Console.WriteLine("Uploading to Blob storage as blob '{0}'", localFileName);
                    Console.WriteLine();

                    // Get a reference to the blob address, then upload the file to the blob.
                    // Use the value of localFileName for the blob name.
                    CloudBlockBlob cloudBlockBlob = cloudBlobContainer.GetBlockBlobReference(localFileName);
                    await cloudBlockBlob.UploadFromFileAsync(sourceFile);

                    // List the blobs in the container.
                    Console.WriteLine("Listing blobs in container.");
                    BlobContinuationToken blobContinuationToken = null;
                    do
                    {
                        var resultSegment = await cloudBlobContainer.ListBlobsSegmentedAsync(null, blobContinuationToken);
                        // Get the value of the continuation token returned by the listing call.
                        blobContinuationToken = resultSegment.ContinuationToken;
                        foreach (IListBlobItem item in resultSegment.Results)
                        {
                            Console.WriteLine(item.Uri);
                        }
                    } while (blobContinuationToken != null); // Loop while the continuation token is not null.
                    Console.WriteLine();

                    // Download the blob to a local file, using the reference created earlier. 
                    // Append the string "_DOWNLOADED" before the .txt extension so that you can see both files in MyDocuments.
                    destinationFile = sourceFile.Replace(".txt", "_DOWNLOADED.txt");
                    Console.WriteLine("Downloading blob to {0}", destinationFile);
                    Console.WriteLine();
                    await cloudBlockBlob.DownloadToFileAsync(destinationFile, FileMode.Create);
                }
                catch (StorageException ex)
                {
                    Console.WriteLine("Error returned from the service: {0}", ex.Message);
                }
                finally
                {
                    Console.WriteLine("Press any key to delete the sample files and example container.");
                    Console.ReadLine();
                    // Clean up resources. This includes the container and the two temp files.
                    Console.WriteLine("Deleting the container and any blobs it contains");
                    if (cloudBlobContainer != null)
                    {
                        await cloudBlobContainer.DeleteIfExistsAsync();
                    }
                    Console.WriteLine("Deleting the local source file and local downloaded files");
                    Console.WriteLine();
                    File.Delete(sourceFile);
                    File.Delete(destinationFile);
                }
            }
            else
            {
                Console.WriteLine(
                    "A connection string has not been defined in the system environment variables. " +
                    "Add a environment variable named 'storageconnectionstring' with your storage " +
                    "connection string as a value.");
            }
        }
    }
}

还有一些其他内置方法可以上传到 Blob 存储,而无需先存储在本地驱动器中。

对于您的情况,您可以考虑以下内置方法:

1.用于上传流(示例请参见here https://github.com/Azure-Samples/storage-blob-dotnet-getting-started/blob/master/BlobStorage/Advanced.cs#L940):

UploadFromStream / UploadFromStreamAsync

2.用于上传字符串/文本(示例请参见here https://github.com/Azure-Samples/storage-blob-dotnet-getting-started/blob/master/BlobStorage/Advanced.cs#L1293):

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

如何将对象传输到 Azure Blob 存储而不将文件保存在本地存储上? 的相关文章

  • 适合初学者的良好调试器教程[关闭]

    Closed 这个问题不符合堆栈溢出指南 help closed questions 目前不接受答案 有谁知道一个好的初学者教程 在 C 中使用调试器 我感觉自己好像错过了很多 我知道怎么做 单步执行代码并查看局部变量 虽然这常常给我带来问
  • 如何在C(Linux)中的while循环中准确地睡眠?

    在 C 代码 Linux 操作系统 中 我需要在 while 循环内准确地休眠 比如说 10000 微秒 1000 次 我尝试过usleep nanosleep select pselect和其他一些方法 但没有成功 一旦大约 50 次 它
  • 如何填充 ToolStripComboBox?

    我发现它很难将数据绑定到ToolStripComboBox 好像没有这个ValueMember and DisplayMember特性 怎么绑定呢 访问toolstripcombobox中包装的组合框并访问其ValueMember Disp
  • 查看 NuGet 包依赖关系层次结构

    有没有一种方法 文本或图形 来查看 NuGet 包之间的依赖关系层次结构 如果您使用的是新的 csproj 您可以在此处获取所有依赖项 在项目构建后 项目目录 obj project assets json
  • C# 数据表更新多行

    我如何使用数据表进行多次更新 我找到了这个更新 1 行 http support microsoft com kb 307587 my code public void ExportCSV string SQLSyntax string L
  • 从客户端访问 DomainService 中的自定义对象

    我正在使用域服务从 Silverlight 客户端的数据库中获取数据 在DomainService1 cs中 我添加了以下内容 EnableClientAccess public class Product public int produ
  • 使用可变参数包类型扩展的 C++ 函数调用者包装器

    我绑定了一些 API 并且绑定了一些函数签名 如下所示 static bool WrapperFunction JSContext cx unsigned argc JS Value vp 我尝试将对象和函数包装在 SpiderMonkey
  • 告诉 Nancy 将枚举序列化为字符串

    Nancy 默认情况下在生成 JSON 响应时将枚举序列化为整数 我需要将枚举序列化为字符串 有一种方法可以通过创建来自定义 Nancy 的 JSON 序列化JavaScript 原始转换器 https github com NancyFx
  • 在 NaN 情况下 to_string() 可以返回什么

    我使用 VS 2012 遇到了非常令人恼火的行为 有时我的浮点数是 NaN auto dbgHelp std to string myFloat dbgHelp最终包含5008角色 你不能发明这个东西 其中大部分为0 最终结果是 0 INF
  • 为什么我的单选按钮不起作用?

    我正在 Visual C 2005 中开发 MFC 对话框应用程序 我的单选按钮是 m Small m Medium 和 m Large 它们都没有在我的 m Summary 编辑框中显示应有的内容 可能出什么问题了 这是我的代码 Pizz
  • C++ 中的双精度型数字

    尽管内部表示有 17 位 但 IEE754 64 位 浮点应该正确表示 15 位有效数字 有没有办法强制第 16 位和第 17 位为零 Ref http msdn microsoft com en us library system dou
  • 高效列出目录中的所有子目录

    请参阅迄今为止所采取的建议的编辑 我正在尝试使用 WinAPI 和 C 列出给定目录中的所有目录 文件夹 现在我的算法又慢又低效 使用 FindFirstFileEx 打开我正在搜索的文件夹 然后我查看目录中的每个文件 使用 FindNex
  • 等待 IAsyncResult 函数直至完成

    我需要创建等待 IAsyncResult 方法完成的机制 我怎样才能做到这一点 IAsyncResult result contactGroupServices BeginDeleteContact contactToRemove Uri
  • 在屏幕上获取字符

    我浏览了 NCurses 函数列表 似乎找不到返回已打印在屏幕上的字符的函数 每个字符单元格中存储的字符是否有可访问的值 如果没有的话Windows终端有类似的功能吗 我想用它来替换屏幕上某个值的所有字符 例如 所有a s 具有不同的特征
  • 使 Guid 属性成为线程安全的

    我的一个类有一个 Guid 类型的属性 该属性可以由多个线程同时读写 我的印象是对 Guid 的读取和写入不是原子的 因此我应该锁定它们 我选择这样做 public Guid TestKey get lock testKeyLock ret
  • Azure 共享计划上的 SSL?

    我有 1 个网站 1 个数据库和 1 个 SSL 托管在 azure 上 我曾经拥有 基本 托管套餐 但每个月要支付 70 美元才能获得基本设置 并且所有内容都具有最小的缩放比例 我意识到我的低流量站点不需要专用计算机 因此我尝试转向共享计
  • String.Empty 与 "" [重复]

    这个问题在这里已经有答案了 可能的重复 String Empty 和 有什么区别 https stackoverflow com questions 151472 what is the difference between string
  • OpenGL:仅获取模板缓冲区而没有深度缓冲区?

    我想获取一个模板缓冲区 但如果可能的话 不要承受附加深度缓冲区的开销 因为我不会使用它 我发现的大多数资源表明 虽然模板缓冲区是可选的 例如 排除它以利于获得更高的深度缓冲区精度 但我还没有看到任何请求并成功获取仅 8 位模板缓冲区的代码
  • 可访问性不一致:参数类型的可访问性低于方法

    我试图在两个表单之间传递一个对象 基本上是对当前登录用户的引用 目前 我在登录表单中有一些类似的内容 private ACTInterface oActInterface public void button1 Click object s
  • OpenCV SIFT 描述符关键点半径

    我正在深入研究OpenCV的SIFT描述符提取的实现 https github com Itseez opencv blob master modules nonfree src sift cpp 我发现了一些令人费解的代码来获取兴趣点邻域

随机推荐

  • 嵌套 ng-repeat 性能

    我听说嵌套 ng repeats 会严重影响 Angular 的性能 如果它会导致大量带有 Angular 表达式的元素 我实际上已经遇到过这种情况 我正在尝试编写一些代码 我尝试使用bindonce https github com Pa
  • R - 从字符串右侧第 n 次出现字符后提取信息

    我见过很多次提取w gsub但它们主要处理从左到右或在一次出现后提取 我想从右到左匹配 数四次出现 匹配第 3 次和第 4 次出现之间的所有内容 例如 string outcome here are some words to try so
  • 在模板化派生类中,为什么需要在成员函数内使用“this->”限定基类成员名称?

    当我调查 Qt 的源代码时 我发现 trolltech 的人明确使用this关键字来访问析构函数上的字段 inline QScopedPointer T oldD this gt d Cleanup cleanup oldD this gt
  • 尽管安装了 Spyder-Terminal,Spyder 5 中仍然没有终端

    我在 Mac OS Big Sur 上安装了 Spyder 5 我从终端运行此命令 conda install spider terminal c spider ide 该命令运行没有错误 仍然没有终端 我一定做错了什么 因为终端没有显示在
  • 使用地图功能

    我遇到了问题map功能 当我想打印创建的列表时 解释器显示指针 gt gt gt squares map lambda x x 2 range 10 gt gt gt print squares
  • 我可以使用 Node.js 阅读 PDF 或 Word 文档吗?

    我找不到任何软件包来执行此操作 我知道 PHP 有大量的 PDF 库 比如http www fpdf org http www fpdf org 但是 Node 有什么用吗 textract https npmjs org package
  • Deno 中子进程如何向父进程发送消息?

    From 这个答案 https stackoverflow com a 62085642 6587634 我知道父进程可以与子进程通信 但是反过来呢 从工人那里你必须使用Worker postMessage https developer
  • SVG 图像在某些 Web 服务器上不显示

    我在某些服务器上的 html 文件中显示 svg 图像时遇到问题 这让我感到困惑 因为我认为是否渲染 svg 图像是由浏览器决定的 但浏览器保持不变 我使用以下字符串来显示它们 img src path to image svg alt i
  • F# 中的全局运算符重载

    我正在开始为笛卡尔积和矩阵乘法定义自己的运算符 将矩阵和向量别名为列表 type Matrix float list list type Vector float list 我可以通过编写自己的初始化代码 并获得笛卡尔积 let inlin
  • pytesseract 错误 Windows 错误 [错误 2]

    您好 我正在尝试使用 python 库 pytesseract 从图像中提取文本 请查找代码 from PIL import Image from pytesseract import image to string print image
  • C++ 中的列表析构函数

    我刚刚实现了链接列表 它工作得很好 但甚至很难 我已经看到我无法在 Node 上创建工作析构函数的符号 这就是为什么它在代码中未实现 我需要在节点上实现工作析构函数 List 的析构函数 但这一个很简单 我将只使用 Node 类的析构函数
  • MySql 数据在第 1 行的“提前”列被截断

    在我的项目中 我使用了 txtAdvance 的关键事件 double gtotal Double parseDouble txtGtotal getText double ad Double parseDouble txtAdvance
  • Rails:如何查询 activerecord 中模型的时间范围(而不是日期)值

    我有一个模型time属性 这是用户想要接收电子邮件的时间 即美国东部时间下午 5 点 的配置 它在数据库中存储为21 00 00 我想按范围查询 例如 我希望每个用户都有一个提醒时间20 55 00 and 21 05 05 Rails 似
  • 如果定义了 item,则 Ansible with_items

    安塞布尔 1 9 4 该脚本应该仅在定义了某些变量的主机上执行某些任务 正常情况下可以正常工作 但与with items陈述 debug var symlinks when symlinks is defined name Create o
  • 如何从 React JS 中的另一个组件获取引用

    主App组件中的代码如下 class App extends Component componentDidMount console log this ref debugger render return div div
  • 更改 Twitter 引导模式中的背景颜色?

    在twitter bootstrap中创建模态时 有什么方法可以更改背景颜色吗 完全删除阴影吗 注意 为了消除阴影 这doesn t有效 因为它也会改变点击行为 我仍然希望能够在模式外部单击以将其关闭 myModal modal backd
  • 如何外部化错误消息

    这是一个外部化错误消息的最佳实践问题 我正在开发一个项目 其中存在代码 简短描述和严重性错误 我想知道外部化此类描述的最佳方式是什么 我想到的是将它们放在代码中是不好的 将它们存储在数据库中 将它们放在属性文件中 或者可能有一个加载了描述的
  • Pandas 查找,将数据框中的一列映射到不同数据框中的另一列

    我有两个 pandas 数据框 df1 和 df2 df1 具有 X 列 Y 列以及 weeknum df2 具有 Z weeknum 和 datetime 列 我基本上想保留 df1 并在其中添加一个额外的列 该列对应 weeknum 的
  • 在 Oracle SQL 中根据时间对重复的分组项运行总计

    我的第一篇文章 所以请耐心等待 我想根据按日期划分的值进行求和 但只需要日期的总和 而不是按项目分组的总和 已经为此工作好几天了 试图避免使用光标 但可能不得不这样做 这是我正在查看的数据的示例 顺便说一句 这是在 Oracle 11g 中
  • 如何将对象传输到 Azure Blob 存储而不将文件保存在本地存储上?

    我一直在关注这个来自 GitHub 的示例 https github com Azure Samples storage blobs dotnet quickstart将文件传输到 Azure Blob 存储 程序在本地创建一个文件MyDo