如何将对象传输到 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 存储而不将文件保存在本地存储上? 的相关文章

  • 结构化绑定中缺少类型信息

    我刚刚了解了 C 中的结构化绑定 但有一件事我不喜欢 auto x y some func is that auto正在隐藏类型x and y 我得抬头看看some func的声明来了解类型x and y 或者 我可以写 T1 x T2 y
  • BASIC 中的 C 语言中的 PeekInt、PokeInt、Peek、Poke 等效项

    我想知道该命令的等效项是什么Peek and Poke 基本和其他变体 用 C 语言 类似PeekInt PokeInt 整数 涉及内存条的东西 我知道在 C 语言中有很多方法可以做到这一点 我正在尝试将基本程序移植到 C 语言 这只是使用
  • STL 迭代器:前缀增量更快? [复制]

    这个问题在这里已经有答案了 可能的重复 C 中的预增量比后增量快 正确吗 如果是 为什么呢 https stackoverflow com questions 2020184 preincrement faster than postinc
  • 根据属性的类型使用文本框或复选框

    如果我有这样的结构 public class Parent public string Name get set public List
  • 在一个数据访问层中处理多个连接字符串

    我有一个有趣的困境 我目前有一个数据访问层 它必须与多个域一起使用 并且每个域都有多个数据库存储库 具体取决于所调用的存储过程 目前 我只需使用 SWITCH 语句来确定应用程序正在运行的计算机 并从 Web config 返回适当的连接字
  • 如何在 Cassandra 中存储无符号整数?

    我通过 Datastax 驱动程序在 Cassandra 中存储一些数据 并且需要存储无符号 16 位和 32 位整数 对于无符号 16 位整数 我可以轻松地将它们存储为有符号 32 位整数 并根据需要进行转换 然而 对于无符号 64 位整
  • 如何在 C++ 中标记字符串?

    Java有一个方便的分割方法 String str The quick brown fox String results str split 在 C 中是否有一种简单的方法可以做到这一点 The 增强分词器 http www boost o
  • 需要帮助优化算法 - 两百万以下所有素数的总和

    我正在尝试做一个欧拉计划 http projecteuler net问题 我正在寻找 2 000 000 以下所有素数的总和 这就是我所拥有的 int main int argc char argv unsigned long int su
  • 重载 (c)begin/(c)end

    我试图超载 c begin c end类的函数 以便能够调用 C 11 基于范围的 for 循环 它在大多数情况下都有效 但我无法理解和解决其中一个问题 for auto const point fProjectData gt getPoi
  • ASP.NET Core 3.1登录后如何获取用户信息

    我试图在登录 ASP NET Core 3 1 后获取用户信息 如姓名 电子邮件 id 等信息 这是我在登录操作中的代码 var claims new List
  • 结构体的内存大小不同?

    为什么第一种情况不是12 测试环境 最新版本的 gcc 和 clang 64 位 Linux struct desc int parts int nr sizeof desc Output 16 struct desc int parts
  • 如何在当前 Visual Studio 主机内的 Visual Studio 扩展中调试使用 Roslyn 编译的代码?

    我有一个 Visual Studio 扩展 它使用 Roslyn 获取当前打开的解决方案中的项目 编译它并从中运行方法 程序员可以修改该项目 我已从当前 VisualStudioWorkspace 成功编译了 Visual Studio 扩
  • C# 动态/expando 对象的深度/嵌套/递归合并

    我需要在 C 中 合并 2 个动态对象 我在 stackexchange 上找到的所有内容仅涵盖非递归合并 但我正在寻找能够进行递归或深度合并的东西 非常类似于jQuery 的 extend obj1 obj2 http api jquer
  • 复制目录下所有文件

    如何将一个目录中的所有内容复制到另一个目录而不循环遍历每个文件 你不能 两者都不Directory http msdn microsoft com en us library system io directory aspx nor Dir
  • 如何实例化 ODataQueryOptions

    我有一个工作 简化 ODataController用下面的方法 public class MyTypeController ODataController HttpGet EnableQuery ODataRoute myTypes pub
  • C 函数 time() 如何处理秒的小数部分?

    The time 函数将返回自 1970 年以来的秒数 我想知道它如何对返回的秒数进行舍入 例如 对于100 4s 它会返回100还是101 有明确的定义吗 ISO C标准没有说太多 它只说time 回报 该实现对当前日历时间的最佳近似 结
  • 如何在 Android 中使用 C# 生成的 RSA 公钥?

    我想在无法假定 HTTPS 可用的情况下确保 Android 应用程序和 C ASP NET 服务器之间的消息隐私 我想使用 RSA 来加密 Android 设备首次联系服务器时传输的对称密钥 RSA密钥对已在服务器上生成 私钥保存在服务器
  • 有没有办法让 doxygen 自动处理未记录的 C 代码?

    通常它会忽略未记录的 C 文件 但我想测试 Callgraph 功能 例如 您知道在不更改 C 文件的情况下解决此问题的方法吗 设置变量EXTRACT ALL YES在你的 Doxyfile 中
  • 对于某些 PDF 文件,LoadIFilter() 返回 -2147467259

    我正在尝试使用 Adob e IFilter 搜索 PDF 文件 我的代码是用 C 编写的 我使用 p invoke 来获取 IFilter 的实例 DllImport query dll SetLastError true CharSet
  • 当文件流没有新数据时如何防止fgets阻塞

    我有一个popen 执行的函数tail f sometextfile 只要文件流中有数据显然我就可以通过fgets 现在 如果没有新数据来自尾部 fgets 挂起 我试过ferror and feof 无济于事 我怎样才能确定fgets 当

随机推荐

  • 嵌套 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