0

以下单元测试失败:

[TestMethod]
public void Add_file_to_blob_and_retrieve_it()
{
    var blobName = Guid.NewGuid().ToString();
    var testFileContents = File.ReadAllText(TestFileSpec);

    Trace.WriteLine(string.Format("Opening blob container {0}", UnitTestBlobAgentName));
    CloudStorageAccount.SetConfigurationSettingPublisher(
            (configName, configSetter) => configSetter(ConfigurationManager.AppSettings[configName]));
    var cloudStorage = CloudStorageAccount.FromConfigurationSetting("StorageConnectionString");
    var blobClient = cloudStorage.CreateCloudBlobClient();
    var container = blobClient.GetContainerReference(UnitTestBlobAgentName.ToLower());

    try
    {
        Trace.WriteLine(string.Format("Uploading file {0}", TestFileSpec));
        var blob = container.GetBlobReference(blobName);
        blob.UploadFile(TestFileSpec);
        blob.Properties.ContentType = "ByteArray";
        blob.SetProperties();
        var blob1 = container.GetBlobReference(blobName);
        var found = blob1.DownloadText();
        Assert.AreEqual(testFileContents.Trim(), found.Trim());
    }
    finally
    {
        if (null != container)
        {
            Trace.WriteLine(string.Format("Deleting blob {0}", blobName));
            var blob2 = container.GetBlobReference(blobName);
            blob2.DeleteIfExists(new BlobRequestOptions { DeleteSnapshotsOption = DeleteSnapshotsOption.IncludeSnapshots });
        }
    }
}

事实证明,返回的字符串以 dword 0xFEFF(Unicode BOM)开头。我已经通过 Microsoft 调试符号进行了跟踪,并且 BOM 存在于返回流中。AFAICT,它来自类中的HttpResponse.GetResponseStream()方法调用方式Microsoft.WindowsAzure.StorageClient.CloudBlob

确保输入和输出相同的最佳方法是什么?在进入之前确保输入转换为Unicode?从输出中剥离 BOM?还有其他想法吗?

4

1 回答 1

2

这是一个旧的,但是如果您的 blob 在 azure 中被编码为 Unicode,并且您想将其下载到文本字符串中,则此代码可以解决问题。请记住,这里的弱点是您必须分配两次内存。如果有更有效的获取 Unicode 字符串的方法(无论如何,同步),我找不到它。

string fileText;
using (var memoryStream = new MemoryStream())
{
    cloudBlob.DownloadToStream(memoryStream);

    memoryStream.Position = 0;

    using (var reader = new StreamReader(memoryStream, Encoding.Unicode))
    {
        fileText = reader.ReadToEnd();
    }
}
于 2014-03-05T20:48:22.430 回答