将文件写入 Azure 存储(文件共享)

Writing file to Azure Storage (File Share)

由于 Microsoft.Azure.Storage.File 已弃用,我们正在尝试升级到 Azure.Storage.Files.Shares.

我们能够移植现有代码以从文件共享中读取文件,但我们无法将更改保存到现有文件。

使用“Microsoft.Azure.Storage.File”我们将流传递给 CloudFile.UploadFromStreamAsync 它会按预期工作。

在“Azure.Storage.Files.Shares”中,我们尝试同时使用两者 ShareFileClient.OpenWriteAsync and ShareFileClient.UploadAsync 但没有成功。

//This seems to empty the file
public void SaveStream(Stream stream)
{
    var openOptions = new ShareFileOpenWriteOptions() { MaxSize = stream.Length + 1 };
    using (var fileStream = File.OpenWrite(true, 0, openOptions))
    {
        stream.CopyToAsync(fileStream);
    }
}

//This corrupts the file (it seems like it appends to it)
public void SaveStream(Stream stream)
{
    File.UploadAsync(stream);
}

stream 是一个 MemoryStreamFile 的一个实例ShareFileClient。我们使用 .NET Standard 2.0。

有谁对此有更多经验,可以进一步阐明这个主题吗?

请尝试更改以下代码:

var openOptions = new ShareFileOpenWriteOptions() { MaxSize = stream.Length + 1 };

var openOptions = new ShareFileOpenWriteOptions() { MaxSize = stream.Length };

通过此更改,我能够更新文件。另外,请确保在使用前,您的源流的位置设置为 0 即流位于开头。

这是我使用的完整代码:

using System;
using System.IO;
using System.Text;
using Azure.Storage.Files.Shares;
using Azure.Storage.Files.Shares.Models;

namespace ConsoleApp1
{
    
    class Program
    {
        static void Main(string[] args)
        {
            string connectionString =
                "DefaultEndpointsProtocol=https;AccountName=account-name;AccountKey=account-key";
            string shareName = "share-name";
            ShareClient shareClient = new ShareClient(connectionString, shareName);
            ShareDirectoryClient directoryClient = shareClient.GetRootDirectoryClient();
            ShareFileClient fileClient = directoryClient.GetFileClient("sample.text");
            string updatedContent = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus pulvinar auctor vehicula. Proin vitae ante risus. Quisque fringilla orci eros, nec fermentum ipsum blandit et. Curabitur imperdiet tristique magna non vehicula. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Sed efficitur magna nisl, vitae venenatis leo semper nec. Nulla consequat lorem sapien, sed aliquam lectus dictum non. Morbi ac pulvinar justo, sit amet cursus turpis. In dictum odio non tellus aliquam viverra. Nunc vel vestibulum nulla. Ut mollis ultrices dignissim. Donec tellus nibh, bibendum suscipit felis sed, elementum auctor est. Donec ex nibh, pellentesque vitae odio ut, ornare pulvinar odio.";
            using MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(updatedContent));
            var openOptions = new ShareFileOpenWriteOptions() { MaxSize = ms.Length };
            using (var fs = fileClient.OpenWrite(true, 0, openOptions))
            {
                ms.CopyTo(fs);
            }
        }
    }
}