gpt4 book ai didi

c# - CloudBlob.DownloadText 方法插入附加字符?

转载 作者:行者123 更新时间:2023-12-03 06:05:15 24 4
gpt4 key购买 nike

以下单元测试失败:

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

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

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

最佳答案

这是一个旧代码,但如果您的 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();
}
}

关于c# - CloudBlob.DownloadText 方法插入附加字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11231147/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com