title: How to save data from stream to file in WinRT?
body: <p>I would like to have a method which takes as an input a System.IO.Stream and use it to write data from it to file. So far I have the following:</p>
  
  <pre><code>    public async Task SaveStreamToFileX(Stream stream, string filePath, IProgress&lt;long&gt; progress)
      {
  
          var folder = await StorageFolder.GetFolderFromPathAsync(Path.GetDirectoryName(filePath));
  
          var fileName = Path.GetFileName(filePath);
          StorageFile file = await folder.CreateFileAsync(fileName, CreationCollisionOption.OpenIfExists);
  
          var istream = stream.AsInputStream();
  
          var canRead = stream.CanRead; //this returns true
  
          using (var reader = new DataReader(istream))
          {
              using (IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.ReadWrite))
              {
                  using (IOutputStream outputStream = fileStream.GetOutputStreamAt(0))
                  {
                      using (DataWriter writer = new DataWriter(outputStream))
                      {
                          IBuffer buffer;
                          long readBytes = 0;
                          const int bufferSize = 8192;
                          while ((buffer = reader.ReadBuffer(bufferSize)).Length &gt; 0) //exception System.Exception with message: Out of range ...
                          {
                              writer.WriteBuffer(buffer);
                              readBytes += bufferSize;
                              progress.Report(readBytes);
                          }
                      }
                  }
              }
          }
  
      }
  </code></pre>
  
  <p>Problem is, that an exception (Out of range) is thrown when I try to read data in while cycle (first read). Stream should have data. I am not sure if so long code is neccesarry, if somebody has better solution it would be great.
  Side note: 
   If I try <code>await reader.LoadAsync(50)</code> it returns 50. I am not sure what LoadAsync should do. Maybe I have to call it before read to prepare data for the read? I will investigate this further ...
   Also, the Stream.CanRead returns true. </p>