首页 > 解决方案 > 如何将数据从本地机器(计算机)推送到 Azure Table

问题描述

我在记事本中创建了一个简单的文本文件,它是一个 .txt 文件。我想将此数据推送到天蓝色表,但我不确定如何在 c# 中执行此操作。有谁知道如何将一些示例数据从我的计算机推送到天蓝色表?谢谢!

标签: c#azure

解决方案


执行此操作需要三个基本步骤:

  1. 将文本文件读入内存

我们可以用一行代码做到这一点:

string text = System.IO.File.ReadAllText(@"C:\Users\Public\TestFolder\WriteText.txt");
  1. 对 Azure 表进行身份验证

您将需要获取 Azure 存储的相关 nuget 包。您可以在没有 SDK 的情况下编写代码,但我不推荐它。

CloudStorageAccount storageAccount = new CloudStorageAccount(
    new Microsoft.WindowsAzure.Storage.Auth.StorageCredentials(
        "<name>", "<account-key>"), true);

// Create the table client.
CloudTableClient tableClient = storageAccount.CreateCloudTableClient();

// Get a reference to a table named "textTable"
CloudTable textTable = tableClient.GetTableReference("textTable");
  1. 写入 Azure 表

我们需要创建一个类来定义我们上传到存储中的数据结构。每个实体都必须有一个行键和一个分区键。

public class TextEntity : TableEntity
{
    public TextEntity(string partitionKey, string rowKey)
    {
        this.PartitionKey = partitionKey;
        this.RowKey = rowKey;
    }

    public TextEntity() { }

    public string Text { get; set; }
}

然后我们可以使用该类来创建我们将上传到存储的对象。

var tableEntry = new TextEntry("partitionKey", "rowKey");
tableEntry.Text = text;

TableOperation insertOperation = TableOperation.Insert(tableEntry);

// Execute the insert operation.
await textTable.ExecuteAsync(insertOperation);

推荐阅读