Is it possible to create a file in Azure File Share without knowing the size ahead of time?

176 Views Asked by At

I'd like to create a file in Azure File Share and stream the contents to the file. I am handed a stream which may not support the .Length property; and the following code will crash due to the stream.Length call:

private async UploadStreamAsync(Stream stream, CancellationToken token = default)
{
  ShareFileClient client = GetShareFileClient();
  await client.CreateAsync(stream.Length, cancellationToken: token);
  await client.UploadAsync(stream, cancellationToken: token);
}

Is there an alternative way to stream a file to Azure File Share without needing to know the size ahead of time?

1

There are 1 best solutions below

0
On

Is there an alternative way to stream a file to Azure File Share without needing to know the size ahead of time?

You can use the below C# code to create a file and stream the content to the file.

Code:

using Azure.Storage.Files.Shares;
using Azure.Storage.Files.Shares.Models;
using System;

namespace FileShareDemo
{
    class Program
    {
        static string connectionString = "your-connection-string";
        static ShareClient shareClient = new ShareClient(connectionString, "Your-filesharename");

        static void Main(string[] args)
        {
            byte[] data = System.Text.Encoding.ASCII.GetBytes("This is the added line.\r\n");

            Upload("filename", data);

            Console.WriteLine("File uploaded with stream successfully.");
        }

        public static void Upload(string filePath, byte[] data)
        {
            ShareFileClient fileShare = new ShareFileClient(connectionString, shareClient.Name, filePath);
            if (!fileShare.Exists())
                fileShare.Create(0);

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

The above code uses a stream to upload a file to Azure File Share without having to know its size beforehand. After creating a ShareFileClient object, the function verifies that the file exists. It creates the file with a size of 0 if it doesn't already exist.

After that, it sets the HTTP headers and retrieves the file's information. Lastly, the data is written to the file by opening a write stream.

Output:

File uploaded with stream successfully.

Portal:

enter image description here

Reference:

ShareFileClient.SetHttpHeaders Method (Azure.Storage.Files.Shares) - Azure for .NET Developers | Microsoft Learn