Ebsan
Ebsan

Reputation: 767

How to properly open and read from a StorageFile multiple times?

In Windows Phone 8.1 (WinRT) I'm grabbing a file from the user's document folder and trying to read through it twice. Once to read each line and get a count of total line for progress tracking purposes. And the second time to actually parse the data. However, on the second pass I get a "File is not readable" type error. So I have a small understanding of what's going on but not entirely. Am I getting this error because the stream of the file is already at the end of the file? Can't I just open a new stream from the same file, or do I have to close the first stream?

Here's my code:

public async Task UploadBerData(StorageFile file)
{
    _csvParser = new CsvParser();
    var stream = await file.OpenAsync(FileAccessMode.Read);

    using (var readStream = stream.AsStreamForRead())
    {
        dataCount = _csvParser.GetDataCount(stream.AsStreamForRead());

        // Set the progressBar total to 2x dataCount.
        // Once for reading, twice for uploading data
        TotalProgress = dataCount * 2;
        CurrentProgress = 0;
    }

    var csvData = _csvParser.GetFileData(stream.AsStreamForRead());
    ...
}

Upvotes: 0

Views: 310

Answers (1)

t4nhpt
t4nhpt

Reputation: 5302

After using the Stream, the position is the end of stream length. You can set it to beginning to read stream again.

Add following line before your parse data function.

stream.Position = 0;

Upvotes: 1

Related Questions