Home > Mobile >  Download and delete file from Azure file shares
Download and delete file from Azure file shares

Time:10-21

I have below code to download files from Azure file shares to local and it works fine.

Is there any way, I can delete the file, once download is completed?

using Azure.Storage.Files.Shares;
using Azure.Storage.Files.Shares.Models;

static void Main(string[] args)
{
    // Get a connection string to our Azure Storage account.
    string connectionString = ConfigurationManager.AppSettings.Get("StorageConnectionString");
    
    // Get a reference to a share named "sample-share"
    ShareClient share = new ShareClient(connectionString, ConfigurationManager.AppSettings.Get("ShareNamed"));
    
    // Get a reference to a directory named "sample-dir"
    ShareDirectoryClient dir = share.GetDirectoryClient(ConfigurationManager.AppSettings.Get("SourceDirectory"));
    
    foreach (ShareFileItem item in dir.GetFilesAndDirectories())
    {
        Console.WriteLine(item.Name);
         // Get a reference to a file named "sample-file" in directory "sample-dir"
        ShareFileClient file = dir.GetFileClient(item.Name);
    
        // Download the file
        ShareFileDownloadInfo download = file.Download();
                    
        using (FileStream stream = File.Open(ConfigurationManager.AppSettings.Get("DestinationDirectory")   item.Name, FileMode.Append))
        {
            download.Content.CopyTo(stream);
            stream.FlushAsync();
            stream.Close();
        }
    
    }
                
    Console.ReadLine();
}

CodePudding user response:

Simply add await file.DeleteAsync to delete the file after you have read the stream.

Something like:

static void Main(string[] args)
{
    // Get a connection string to our Azure Storage account.
    string connectionString = ConfigurationManager.AppSettings.Get("StorageConnectionString");

    // Get a reference to a share named "sample-share"
    ShareClient share = new ShareClient(connectionString, ConfigurationManager.AppSettings.Get("ShareNamed"));

    // Get a reference to a directory named "sample-dir"
    ShareDirectoryClient dir = share.GetDirectoryClient(ConfigurationManager.AppSettings.Get("SourceDirectory"));

    foreach (ShareFileItem item in dir.GetFilesAndDirectories())
    {
        Console.WriteLine(item.Name);
        // Get a reference to a file named "sample-file" in directory "sample-dir"
        ShareFileClient file = dir.GetFileClient(item.Name);

        // Download the file
        ShareFileDownloadInfo download = file.Download();
        
        using (FileStream stream = File.Open(ConfigurationManager.AppSettings.Get("DestinationDirectory")   item.Name, FileMode.Append))
        {
            download.Content.CopyTo(stream);
            stream.FlushAsync();
            stream.Close();
        }
        await file.DeleteAsync();
    }
    
    Console.ReadLine();
}
  • Related