0

我想将使用“Microsoft.Azure.Storage.File”的方法重写为“Azure.Storage.Files.Shares”。此方法是使用 sasuri 将文件复制到文件共享。

    /// <summary>
    /// Data model for attachment content
    /// </summary>
    public class Attachment
    {
      /// <summary>
      /// File Name
      /// </summary>
      public string FileName { get; set; }

      /// <summary>
      /// FileContent
      /// </summary>
      public string Content { get; set; }
    
     /// <summary>
     /// File Type
     /// </summary>
     public string ContentType { get; set; }
   }

    /// <summary>
    /// CopyFileToShareAsync
    /// </summary>
    /// <param name="sasUri"></param>
    /// <param name="attachment"></param>
    /// <returns></returns>
    public async Task CopyFileToShareAsync(string sasUri, Attachment attachment)
    {
        var cloudFileDirectory = new CloudFileDirectory(new Uri(sasUri));

        var cloudFile = cloudFileDirectory.GetFileReference(attachment.FileName);

        byte[] bytes = Convert.FromBase64String(attachment.Content);

        await cloudFile.UploadFromStreamAsync(new MemoryStream(bytes));
    }
4

1 回答 1

1

请尝试以下操作:

class Program
{
    static void Main(string[] args)
    {
        string sasUri = "https://account-name.file.core.windows.net/share-name?sv=2020-04-08&se=2021-03-30T18%3A30%3A00Z&sr=s&sp=cw&sig=ZYXpOsCwP6uBOudbEu3TWwBAPc%2BOefu%2B%2F0lKl5ls3k8%3D";
        Attachment attachment = new Attachment()
        {
            FileName = "sample.text",
            Content = Convert.ToBase64String(Encoding.UTF8.GetBytes("Some content")),
            ContentType = "text/plain"
        };
        CopyFileToShareAsync(sasUri, attachment).GetAwaiter().GetResult();
        Console.WriteLine("Content uploaded");
    }

    static async Task CopyFileToShareAsync(string sasUri, Attachment attachment)
    {
        ShareDirectoryClient shareDirectoryClient = new ShareDirectoryClient(new Uri(sasUri));
        ShareFileClient shareFileClient = shareDirectoryClient.GetFileClient(attachment.FileName);
        byte[] fileContent = Convert.FromBase64String(attachment.Content);
        await shareFileClient.CreateAsync(fileContent.Length, new Azure.Storage.Files.Shares.Models.ShareFileHttpHeaders()
        {
            ContentType = attachment.ContentType
        });
        using (MemoryStream ms = new MemoryStream(fileContent))
        {
            await shareFileClient.UploadAsync(ms);
        }
    }
}

public class Attachment
{
    /// <summary>
    /// File Name
    /// </summary>
    public string FileName { get; set; }

    /// <summary>
    /// FileContent
    /// </summary>
    public string Content { get; set; }

    /// <summary>
    /// File Type
    /// </summary>
    public string ContentType { get; set; }
}
于 2021-03-19T06:27:14.127 回答