Download file from fileshare azure storage

In earlier post, we have seen how to upload file to FileShare component of Azure storage system, in this post we learn how to download file from azure file storage and delete a file from azure cloud. you can learn more about Azure file share.

image file share

This example is written using asp.net core 3.1 framework c# with razor page application.

Before we can download or delete any particular file, we have to get the list of all azure cloud files from fileshare storage, and display in our razor page, then we can take action on any file we want.

using Microsoft.Extensions.Configuration;
using Microsoft.WindowsAzure.Storage;
using Azure.Storage.Files.Shares;
using Azure;
using System.Net.Http;
using Microsoft.Extensions.FileProviders;


public class fileManagerModel : PageModel
{         
	private readonly IConfiguration _configuration;
	 
	public fileManagerModel(IConfiguration configuration)
	{            
		_configuration = configuration;
	}    
	[BindProperty]
	public List<AzFile> FoldersFiles { get; set; }
	
	public async void OnGet()
	{            
		HttpContext.CheckAdminSession();
		await GetAllFiles();
	}
}

So I have created a custom class called "AzFile", to keep record of each file attributes

public class AzFile
{
    public AzFile()
    {         
    }
    public string Id { get; set; }
    public string DirName { get; set; }
    public string Name { get; set; }
    public string Url { get; set; }
    public string ETag { get; set; }
    public bool IsDirectory { get; set; } = false;
    public string Modified { get; set; }
}

As you can see there is property in my page called FoldersFiles public List<AzFile> FoldersFiles { get; set; }. when the page is loaded, this property will have the list of all files.

public async Task GetAllFiles()
{  
	List<AzFile> _result = await GetShareFilesAsync();
	FoldersFiles = _result; 
}

In above code we have called a method named "GetShareFilesAsync", now let's look at the code to understand how all files from filestorage accont.



async  Task<List<AzFile>> GetShareFilesAsync()
{
	string _azureStorageConnection = _configuration.GetSection("AzureStorage")["ConnectionString"];
	  
	// Name of the share, directory
	string shareName = "sharename1";

	// if dir name is empty, it will loop through all folders 
	string dirName = "";

	List<AzFile> result = new List<AzFile>();

	// Get a reference to a share
	ShareClient share = new ShareClient(_azureStorageConnection, shareName);

	ShareDirectoryClient directory = share.GetDirectoryClient(dirName);

	var files = directory.GetFilesAndDirectories();

	foreach (var file in files)
	{
		if (file.IsDirectory)
		{
			result.Add(new AzFile()
			{
				Name = file.Name,
				Id = file.Id,
				DirName = file.Name,
				IsDirectory = file.IsDirectory
			});
			directory = share.GetDirectoryClient(file.Name);
			files = directory.GetFilesAndDirectories();
			foreach (var file1 in files)
			{
				result.Add(new AzFile()
				{
					Name = file1.Name,
					DirName = file.Name,
					Id = file1.Id,
					Modified = file1.Properties.LastModified.ToString(),
					IsDirectory = file1.IsDirectory,
					ETag = file1.Properties.ETag.ToString()
				});
			};
		}
		else
		{
			result.Add(new AzFile()
			{
				Name = file.Name,
				DirName = file.Name,
				Id = file.Id,
				Modified = file.Properties.LastModified.ToString(),
				ETag = file.Properties.ETag.ToString()
			});
		}
	}
	return await Task.FromResult(result);
}

Now let’s display the file list on razor page. So I am just checking if “FoldersFiles” property is not null, then looping through the list of all files from axure cloud fileshare storage.

@if (Model.FoldersFiles != null)
{
	foreach (AzFile s in Model.FoldersFiles)
	{
		<div>
			@s.Id | @s.Name | @s.DirName | @s.ETag;
			@if (!s.IsDirectory)
			{
			<div>
				<a href="filedel1?name=@s.Name&dir=@s.DirName">Delete</a> |
				<a download href="@Url.Page("downloadfile", "DownloadFileFromCloud", new { name = @s.Name, dir = @s.DirName })">Download File</a>
			</div>
			}
		</div>
	}
}

download file from azure fileshare

As you can see in above code, for each file I am calling the download and delete action, for download I am calling “DownloadFileFromCloud”

<a download href="@Url.Page("downloadfile", "DownloadFileFromCloud", new { name = @s.Name, dir = @s.DirName })">Download File</a>

Now we write a method which will return a FileResult based on file name we provide, in code below i have written "DownloadFileFromCloud", which convert the Stream data into a file of specified type.

public FileResult OnGetDownloadFileFromCloud(string fileName, string directoryName)
    {
        
        string _storageConnection = _configuration.GetSection("AzureStorage")["ConnectionString"];
        string _shareName = _configuration.GetSection("AzureStorage")["defaultFileShare"];
        
        // Get a reference to a share
        ShareClient share = new ShareClient(_storageConnection, _shareName);
        
        ShareDirectoryClient _directory = share.GetDirectoryClient(directoryName);
        
        ShareFileClient myFile = _directory.GetFileClient(fileName);
        
        Stream _stream =  myFile.OpenReadAsync().Result;
        
        ShareFileProperties _prop=  myFile.GetProperties();
                        
        // return the file
        return File(_stream, _prop.ContentType, fileName);
    }

Now on click of each download link every file will be downloaded in your local download folder.

delete file from azure file storage

Similarly, for delete we have different function, which we call on page load of some other page.

public async void OnGet()
{
HttpContext.CheckAdminSession();
var _name = Request.Query["name"];
var _dirName = Request.Query["dir"];
if (!string.IsNullOrEmpty(_name))
{
CurrentFileName = _name;
await DeleteFileFromCloudStorage(_name, _dirName);
            HttpContext.Response.Redirect("filemgr1");
        }
    }




async Task<IActionResult> DeleteFileFromCloudStorage(string fileName, 
    string dirName)
{
    string _storageConnection = _configuration.GetSection("AzureStorage")["ConnectionString"];
    string _shareName = _configuration.GetSection("AzureStorage")["defaultFileShare"];
        
    // Get a reference to a share
    ShareClient share = new ShareClient(_storageConnection, _shareName);             
        
    ShareDirectoryClient _directory = share.GetDirectoryClient(dirName);
        
    ShareFileClient myFile = _directory.GetFileClient(fileName);
    await myFile.DeleteIfExistsAsync();

    return Redirect("filemgr1");
} 

Calling "DeleteIfExistsAsync" will be always safe, it will delete if exists, otherwise no additional check required in our code.

 
Azure Cloud Tutorial
learn azure cloud development

Let's learn how to use Azure Cloud Storage system from Ap.net core c# application.

Data Analysis
learn Artificial Intelligence
download and delete from Azure file storage
Learn Azure Cloud Development