gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 23:58:44 26 4
gpt4 key购买 nike

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

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

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

在“Azure.Storage.Files.Shares”中,我们尝试同时使用 ShareFileClient.OpenWriteAsyncShareFileClient.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);
}

streamMemoryStreamFileShareFileClient的实例。我们使用 .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);
}
}
}
}

关于c# - 将文件写入 Azure 存储(文件共享),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67890282/

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