C# 生成 Azure Table 存储连接字符串

C# Generate Azure Table Storage ConnectionString

我想使用 azure subscriptionId 和 azureApiKey 为 azure table 存储生成连接字符串。

我找到了以下 Microsoft 库:https://github.com/Azure/azure-libraries-for-net/tree/master 但无法理解如何在此处生成 connectionString。我什至找不到合适的方法。

我需要额外的数据来生成 ConnectionString 吗?

你真的不需要生成它,你可以进入 Azure 门户并创建一个存储帐户任何复制连接字符串:

但是,如果你想生成它,你可以只用你的账户名和密钥填充这个字符串: "DefaultEndpointsProtocol=https;AccountName={yourAccountName};AccountKey={yourAccountKey};EndpointSuffix=core.windows.net"

如果你想使用.net库,你可以在这里找到例子: https://github.com/Azure-Samples/storage-dotnet-manage-storage-accounts

Do I need additional data to generate ConnectionString?

准备:

1.Registry Azure AD 中的应用程序并创建用于访问资源的服务主体。更多详情请参考document.

2.Prepare认证文件,内容如下格式。这些值可以从步骤 1 中获得。

subscription=########-####-####-####-############
client=########-####-####-####-############
key=XXXXXXXXXXXXXXXX
tenant=########-####-####-####-############
managementURI=https\://management.core.windows.net/
baseURL=https\://management.azure.com/
authURL=https\://login.windows.net/
graphURL=https\://graph.windows.net/

3.Install 项目中的库 Microsoft.Azure.Management.Fluent and Microsoft.Azure.Management.ResourceManager.Fluent

演示代码:

var credFile = @"auth file path"; // example: c:\tom\auth.txt
var keyName = "key1";
var azure = Azure
            .Configure()
            .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
            .Authenticate(credentials)
            .WithDefaultSubscription(); 
var storageAccount = azure.StorageAccounts.GetByResourceGroup(resourceGroupName, storageName);
var key = storageAccount.RegenerateKey(keyName);
var connectionString = $"DefaultEndpointsProtocol=http;AccountName={storageAccount.Name};AccountKey={key.FirstOrDefault()?.Value}";        

测试结果: