Search code examples
c#.netazurefileshare

How to create ShareFileClient without specifying it's size to be able to stream data to it?


I would like to create new blob on FileShareClient in Azure FileShare resource with .NET api. I cannot specify it's size in the beginning (because it will be filled with data later eg. csv file filled with lines, up to couple of GBs).

I was trying to use something like this in my code:

using Azure.Storage.Files.Shares

  ShareFileClient fileShare = new ShareFileClient(
            "MYConnectionString",
            "FileShareName",
            "TestDirectoryName");
  if (!fileShare.Exists())
        {
            fileShare.Create(0);
        }
var stream = fileShare.OpenWrite(true, 0);

[Edit] I have got an exception: System.ArgumentException: 'options.MaxSize must be set if overwrite is set to true' Is there any way to avoid specyfining this size?


Solution

  • Micro$ofts infinite wisdom: resize is hidden in SetHttpHeaders method.

    public void AppendFile(string filePath, byte[] data)
    {
        ShareFileClient fileShare = new ShareFileClient(connectionString, shareClient.Name, filePath);
        if (!fileShare.Exists())
            fileShare.Create(0);
    
        for (int i = 0; i < 10; i++)
        {
            var properties = fileShare.GetProperties();
            var openOptions = new ShareFileOpenWriteOptions();
    
            fileShare.SetHttpHeaders(properties.Value.ContentLength + data.Length);
    
            var stream = fileShare.OpenWrite(false, properties.Value.ContentLength, openOptions);
    
            stream.Write(data, 0, data.Length);
    
            stream.Flush();
        }
    }