This code always returns an empty string
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 ""
}
}
}
I'm trying to read the last 20% of the file instead of downloading the whole thing then reading the last 20%. Don't even need the last 20% just need to read the last line (its a text file). Is there something that's missing here or some other azure method I could use to achieve this?
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: