SharefileClient's UploadRangeAsync overrides with blank spaces previous content when adding more text to a file (C#)

291 Views Asked by At

I'm creating a method to append new text to an existing file in an Azure File Share. This is the code:

 public async Task AppendAllTextAsync(string path, string text)
        {
            var fileClient = _fileShare.GetRootDirectoryClient().GetFileClient(path);

            var currentFileLength = fileClient.GetProperties().Value.ContentLength;

            using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(text)))
            {
                await fileClient.CreateAsync(currentFileLength + ms.Length);
                await fileClient.UploadRangeAsync(new HttpRange(currentFileLength - 1, ms.Length), ms);
            }
        }

When I test with a sample txt file whose initial content is this: Sample text file

it removes all the content and append the content at the end. For example, if I call my method like this on the said file accessor.AppendAllText("Sample file.txt", " 2");

Then the file shows: Sample file after appending text

So it's like removing all the previous content when offsetting.

Any ideas on why it's happening or a way of doing this correctly?

1

There are 1 best solutions below

1
Fabiana Minardi On
Dim Byt As Byte() = MSt.ToArray
Dim currentFileLength As Long = (Await File.GetPropertiesAsync()).Value.ContentLength
Await File.SetHttpHeadersAsync(currentFileLength + Byt.Length)
Dim SFW As Stream = Await File.OpenWriteAsync(overwrite:=False, position:=currentFileLength)
Await SFW.WriteAsync(Byt, 0, Byt.Length)
Await SFW.FlushAsync()