从 Azure 文件共享下载和删除文件

Download and delete file from Azure file shares

我有以下代码可以将文件从 Azure 文件共享下载到本地,并且工作正常。

下载完成后,有什么办法可以删除文件吗?

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();
}

只需添加await file.DeleteAsync即可在阅读流后删除文件。

类似于:

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();
}