Last Access Time of the Azure storage files

1.9k Views Asked by At

Is there way to determine Last Access Time of the Azure storage files apart from log analytics . So, does anyone ever come across this situation, what would be the best way to achieve this? Or am I too concerned about this?

Thank you in advanced.

2

There are 2 best solutions below

0
On

In Azure file storage, there is no option till date to know the last opened/viewed/accessed time, but there is a possibility to get to know about the last modified file. In case you are looking for that, here's a C# way:

CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse("<Your Connection string>");
CloudFileClient cloudFileClient = cloudStorageAccount.CreateCloudFileClient();
CloudFileShare cloudFileShare = cloudFileClient.GetShareReference("<Your File Share Name>");
IEnumerable<IListFileItem> fileShareItemsList = cloudFileShare.GetRootDirectoryReference().ListFilesAndDirectories();

foreach (IListFileItem listItem in fileShareItemsList)
{
  if (listItem is CloudFile) // Checking direct files under the root directory for now
  {
    CloudFile file = (CloudFile)listItem;
    file.FetchAttributes(); // this is mandatory to fetch modified time
    DateTime lastModifiedTime = file.Properties.LastModified; // Here's the time!
    // Use it in your logic..
  }
}

0
On

To elaborate on what Deeppak put, another "solution" with a C# that you can do is modify the tags of a blob. Blobs support up to 12 unique tags; adding one with a key like "LastAccessedTimeStamp" and adding/updating it when the file is accessed is a simple way of achieving the goal since Azure still doesn't natively support the last access auditing. I broke it up into two different functions since I would need to update the timestamp in various places of my code.

    public async Task UpdateBlobLastAccessedTimeStamp(string blobName,
        string fileName)
    {
        var client = new BlobServiceClient(new Uri(_shareSettings.SecretUrl));
        var containerClient = client.GetBlobContainerClient(_shareSettings.ContainerName.ToString());
        var blobClient = containerClient.GetBlobClient(blobName);
        await UpdateBlobLastAccessTimeStamp(blobClient);
    }
    
     private async Task UpdateBlobLastAccessTimeStamp(BlobClient client)
    {
        var tagsResponse = await client.GetTagsAsync();
        var tags = tagsResponse.Value?.Tags ?? 
                   new Dictionary<string, string>();
        var containsKeys = tags.ContainsKey(_azureAccessedTagName);
        if (containsKeys)
        {
            tags[_azureAccessedTagName] = DateTime.Now.ToUniversalTime()
                .ToString(CultureInfo.InvariantCulture);
        }
        else
        {
            tags.Add(_azureAccessedTagName,DateTime.Now.ToUniversalTime()
                .ToString(CultureInfo.InvariantCulture));
        }

        await client.SetTagsAsync(tags);
    }