3

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?

Jack n J
  • 206
  • 3
  • 14

2 Answers2

3

Please try to use the latest package Azure.Storage.Files.Shares, version 12.5.0.

Note, in the code new ShareFileClient(), the last parameter is the directory name + file name.

see the code below:

        ShareFileClient f2 = new ShareFileClient(connectionString, shareName, dirName + "/test.txt");
        if (!f2.Exists())
        {
            f2.Create(0);
        }

The file with 0 size can be created, here is the test result:

enter image description here

Ivan Glasenberg
  • 29,865
  • 2
  • 44
  • 60
  • I have tried your solution but when i try to open write in this way: var stream = f2.OpenWrite(true, 0); 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? – Jack n J Dec 14 '20 at 10:36
  • @JacknJ, the answer is no if you set `true` for `OpenWrite` method. And if you want to overwrite the file, it's easy to set the MaxSize(and it should be larger the data you want to upload). For example: `ShareFileOpenWriteOptions options = new ShareFileOpenWriteOptions{ MaxSize = 30}; var openwrite_stream = f2.OpenWrite(true, 0,options:options);` – Ivan Glasenberg Dec 15 '20 at 02:54
  • @JacknJ, Hello, if the answer is helpful, could you please accept it as answer:). Thanks. And if you still have more issues, please @ me. – Ivan Glasenberg Dec 18 '20 at 01:17
2

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();
    }
}
    
Artur G
  • 36
  • 3