gpt4 book ai didi

c# - 从 Azure 文件共享下载并删除文件

转载 作者:行者123 更新时间:2023-12-03 01:21:48 26 4
gpt4 key购买 nike

我有以下代码可将文件从 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();
}

关于c# - 从 Azure 文件共享下载并删除文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69631244/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com