如何附加到 Azure 存储文件共享中的文件? [英] How do I append to a file in an Azure storage file share?

查看:23
本文介绍了如何附加到 Azure 存储文件共享中的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将条目写入存储在 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}\r\n");

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);
}

这篇关于如何附加到 Azure 存储文件共享中的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆