Search code examples
c#.netazurefileshare

How to open ShareFileClient write stream with specific encoding type?


I would like to create new blob on FileShareClient in Azure FileShare resource with .NET api. Is there any way to specify it's encoding while doing this operation? To open write files I use something like this:

  public Stream FileShareOpenWrite(Response<ShareFileProperties> properties, ShareFileOpenWriteOptions openOptions)
    {
        return shareFileClient.OpenWrite(false, properties.Value.ContentLength, openOptions);
    }

Is there any possibility to specify encoding while open ShareFileClient's writer?

For local files i have similar function which creates new StreamWriter and allows me to specify encoding to ANSI directly:

     using (var writer = new StreamWriter(userInputModel.Path, true, Encoding.GetEncoding("ISO-8859-1")))

Solution

  • If you want to set the encoding of Azure file in file share, we can use the rest API Set File Properties, and then set x-ms-content-encoding in the request header.

    For code, if you're using azure file storage sdk, you can refer to this article.

    For example

    ShareClient share = new ShareClient(connectionString, shareName);
    ShareDirectoryClient directory = share.GetDirectoryClient(dirName);
    ShareFileClient file = directory.GetFileClient(fileName);
    
    if(await file.ExistsAsync()){
    
      file.SetHttpHeadersAsync(<file size>, new ShareFileHttpHeaders(){ContentEncoding = {""}})
    }else{
     file.CreateAsync (<file size>, new ShareFileHttpHeaders(){ContentEncoding = {""}})
    }