如何获取Azure Table创建日期?实现旧表便捷删除
你说得没错,CloudTable类确实没直接提供创建日期属性,不过完全不用妥协把时间塞进表名里——有几种更优雅的方法可以获取Azure Table的创建时间,下面给你逐一说明:
获取Azure Table创建日期的几种方法
1. 使用最新的Azure.Data.Tables SDK(推荐)
微软新推出的Azure.Data.Tables SDK已经把表的创建时间作为原生属性暴露出来了,用起来非常省心。示例代码如下:
using Azure.Data.Tables; // 初始化TableServiceClient var tableServiceClient = new TableServiceClient("你的存储账户连接字符串"); // 获取指定表的信息 var tableItem = await tableServiceClient.GetTableAsync("目标表名称"); if (tableItem != null) { // CreatedOn就是表的创建时间 DateTimeOffset? creationTime = tableItem.Value.CreatedOn; Console.WriteLine($"该表创建于:{creationTime?.ToString("yyyy-MM-dd HH:mm:ss")}"); }
2. 使用旧版Microsoft.Azure.Cosmos.Table SDK(兼容CloudTable)
如果还在使用基于CloudTable的旧版SDK,虽然没有直接的属性,但可以通过调用FetchAttributesAsync()后从响应头中提取创建时间:
using Microsoft.Azure.Cosmos.Table; using System.Linq; var storageAccount = CloudStorageAccount.Parse("你的存储账户连接字符串"); var tableClient = storageAccount.CreateCloudTableClient(); var targetTable = tableClient.GetTableReference("目标表名称"); // 获取表的属性信息 await targetTable.FetchAttributesAsync(); // 从响应头中获取x-ms-creation-time字段 var creationTimeHeader = targetTable.ServiceClient.HttpClient.DefaultRequestHeaders .GetValues("x-ms-creation-time") .FirstOrDefault(); if (!string.IsNullOrEmpty(creationTimeHeader)) { DateTime creationTime = DateTime.Parse(creationTimeHeader, null, System.Globalization.DateTimeStyles.RoundtripKind); Console.WriteLine($"该表创建于:{creationTime.ToString("yyyy-MM-dd HH:mm:ss")}"); }
3. 批量查询用Azure Resource Graph
如果需要一次性查询多个存储账户下所有表的创建时间,Azure Resource Graph是最高效的方式,用Kusto查询语句就能批量获取:
resources | where type == "microsoft.storage/storageaccounts/tableservices/tables" | project 表名称 = name, 资源组 = resourceGroup, 订阅ID = subscriptionId, 创建时间 = properties.createdTime
你可以在Azure门户的Resource Graph Explorer中执行这个查询,或者通过SDK集成到自己的管理工具里。
这些方法都能帮你避开把创建时间嵌到表名里的麻烦,根据你的SDK版本和使用场景选合适的就行。
内容的提问来源于stack exchange,提问作者daxu
相关产品推荐
相关产品推荐

