Hay*_*ore 7 .net c# azure azure-storage-blobs
我目前正在尝试使用 DownloadToStream 方法从 Azure blob 存储下载文件,以将 blob 的内容下载为文本字符串。但是我没有得到任何东西,而是一个空字符串。
这是我用来连接到 azure blob 容器并检索 blob 文件的代码。
public static string DownLoadFroalaImageAsString(string blobStorageName, string companyID)
{
// Retrieve storage account from connection string.
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
CloudConfigurationManager.GetSetting("StorageConnectionString"));
// Create the blob client.
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
// Retrieve reference to a previously created container.
CloudBlobContainer container = blobClient.GetContainerReference(companyID.ToLower());
//retrieving the actual filename of the blob
string removeString = "BLOB/";
string trimmedString = blobStorageName.Remove(blobStorageName.IndexOf(removeString), removeString.Length);
// Retrieve reference to a blob named "trimmedString"
CloudBlockBlob blockBlob2 = container.GetBlockBlobReference(trimmedString);
string text;
using (var memoryStream = new MemoryStream())
{
blockBlob2.DownloadToStream(memoryStream);
text = System.Text.Encoding.UTF8.GetString(memoryStream.ToArray());
}
return text;
}
Run Code Online (Sandbox Code Playgroud)
我一直在关注这个文档,但是我似乎无法让它工作。任何帮助将不胜感激。
Tom*_*SFT 13
但是我没有得到任何东西,而是一个空字符串。
我在我这边测试了你提供的代码,它工作正常。我假设在您的情况下测试 blob 内容为空。我们可以通过以下方式解决问题:
1.请尝试检查memoryStream的长度。如果长度等于 0,我们就可以知道 blob 内容是空的。
using (var memoryStream = new MemoryStream())
{
blockBlob2.DownloadToStream(memoryStream);
var length = memoryStream.Length;
text = System.Text.Encoding.UTF8.GetString(memoryStream.ToArray());
}
Run Code Online (Sandbox Code Playgroud)
2.我们可以将包含内容的 blob 上传到容器,我们可以使用 Azure 门户或Microsoft Azure 存储资源管理器轻松做到这一点 。并请尝试使用上传的 blob 测试它。
如果您想从 blob 中获取文本,可以使用 DownloadTextAsync()
var text = await blockBlob2.DownloadTextAsync();
Run Code Online (Sandbox Code Playgroud)
如果要将文件流返回给 API 响应,可以使用 FileStreamResult,即 IActionResult。
var stream = await blockBlob2.OpenReadAsync();
return File(stream, blockBlob2.Properties.ContentType, "name");
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
16640 次 |
最近记录: |