如何追加到 Azure 存储文件共享中的文件?文件共享、文件、Azure

2023-09-07 02:23:10 作者:人生若如初见

我想将条目写入存储在 Azure 文件存储中的日志文件.我目前有这个:

I want to write entries to a log file stored in Azure file storage. I currently have this:

var log = "My log entry";

var client = _storageAccount.CreateCloudFileClient();
var share = client.GetShareReference(Config.LogShare);
share.CreateIfNotExists();
var root = share.GetRootDirectoryReference();
var logfile = root.GetFileReference("log.txt");
if (!logfile.Exists()) logfile.Create(0);

// What goes here to append to the file...?

我可以看到很多关于如何使用 Blob 执行此操作的示例,或者如何上传整个文件,但我如何仅追加到现有文件?

I can see plenty of examples of how to do this with Blobs, or how to upload an entire file, but how do I just append to an existing file?

我试过这个:

var buffer = Encoding.GetEncoding("UTF-8").GetBytes(log.ToCharArray());

using (var fileStream = logfile.OpenWrite(0)) {
    fileStream.Write(buffer, (int)logfile.Properties.Length, buffer.Length);
}

然后我得到这个错误:

The remote server returned an error: (416) The range specified is invalid for the current size of the resource..

推荐答案

我自己解决了这个问题.您只需要将文件的大小增加您要写入的新字节数,然后将新数据写入文件末尾的新空白空间,如下所示:

I managed to work this out myself. You just need to increase the size of the file by the number of new bytes you want to write to it, and then write the new data to that new empty space at the end of the file, like this:

var client = _storageAccount.CreateCloudFileClient();
var share = client.GetShareReference(Config.LogShare);
share.CreateIfNotExists();
var root = share.GetRootDirectoryReference();
var logfile = root.GetFileReference("log.txt");
if (!logfile.Exists()) logfile.Create(0);

var buffer = Encoding.UTF8.GetBytes($"{log}
");

logfile.Resize(logfile.Properties.Length + buffer.Length);

using (var fileStream = logfile.OpenWrite(null)) {
    fileStream.Seek(buffer.Length * -1, SeekOrigin.End);
    fileStream.Write(buffer, 0, buffer.Length);
}