此代码始终返回一个空字符串
CloudFile cFile = fShare.getFile(subDir, rootDir, logFileName, AzureConstants.PATH);
if (cFile.Exists())
{
using (var ms = new MemoryStream())
{
long?offset =Convert.ToInt64(cFile.Properties.Length * .8);
long? length = Convert.ToInt64(cFile.Properties.Length * .20);
cFile.DownloadRangeToStream(ms, offset, length);
using (var sr = new StreamReader(ms))
{
return sr.ReadToEnd();// this does run and it returns an empty string ""
}
}
}
我正在尝试读取文件的最后20%,而不是先下载整个内容,然后再阅读最后20%。甚至不需要最后20%的内容,只需阅读最后一行(它是一个文本文件)即可。这里是否缺少某些东西,或者我可以使用其他一些蔚蓝的方法来实现这一目标?
答案 0 :(得分:1)
You forgot to set the memory stream's position to zero before use StreamReader.
Sample code as below:
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Auth;
using Microsoft.WindowsAzure.Storage.File;
using System;
using System.IO;
namespace ConsoleApp19
{
class Program
{
static void Main(string[] args)
{
string s1 = "";
CloudStorageAccount storageAccount = new CloudStorageAccount(new StorageCredentials("your account", "your key"), true);
CloudFileClient fileClient = storageAccount.CreateCloudFileClient();
CloudFileShare share = fileClient.GetShareReference("t11");
CloudFileDirectory rootDir = share.GetRootDirectoryReference();
CloudFile file =rootDir.GetFileReference("test.txt");
if (file.Exists())
{
using (var ms = new MemoryStream())
{
long? offset = Convert.ToInt64(file.Properties.Length * .8);
long? length = Convert.ToInt64(file.Properties.Length * .20);
file.DownloadRangeToStream(ms, offset, length);
//set the position of memory stream to zero
ms.Position = 0;
using (var sr = new StreamReader(ms))
{
s1 = sr.ReadToEnd();
}
Console.WriteLine(s1);
}
}
Console.WriteLine("---done---");
Console.ReadLine();
}
}
}
My test file: