Daniel
Daniel

Reputation: 109

UWP - RandomAccessStream quits when the file is modified

I am trying to read the contents of a file while new lines are being added. For that I have the following code in place.

using (var inputStream = await file.OpenAsync(FileAccessMode.Read, StorageOpenOptions.AllowOnlyReaders))
        using (var streamReader = new StreamReader(inputStream.AsStream()))
        {
            string line;
            while ((line = streamReader.ReadLine()) != null)
            {
            }
            streamReader.Close();
            inputStream.Dispose();
        }

The problem is that as soon as the file is modified the inputstream has the size 0 and the loop quits.

How do I work around that?

Upvotes: 0

Views: 54

Answers (1)

Daniel
Daniel

Reputation: 109

For anyone having the same issue, this seems to work.

The important part is the oldsize variable. You need to have the if clause, or else it wont work.

using (var randAccessStream = await file.OpenAsync(FileAccessMode.Read, StorageOpenOptions.AllowReadersAndWriters))
        using (var inputStream = randAccessStream.AsStream())
        using (var streamReader = new StreamReader(inputStream))
        {
            var oldsize = randAccessStream.Size;
            string line;
            while ((line = streamReader.ReadLine()) != null)
            {
                if (oldsize != randAccessStream.Size) //Useless but seems to fix the bug
                {
                    oldsize = randAccessStream.Size;
                    await Task.Delay(100);
                }
            }

            await inputStream.FlushAsync();
            streamReader.Close();
            inputStream.Dispose();
            randAccessStream.Dispose();
        }

Upvotes: 1

Related Questions