Write To String to Stream - CSharp File IO

CSharp examples for File IO:Text File

Description

Write To String to Stream

Demo Code


using System.Threading.Tasks;
using System.Text;
using System.Linq;
using System.IO;//from w w  w . j  ava2  s.com
using System.Collections.Generic;
using System;

public class Main{
        public static Task<string> WriteToString(Func<Stream, Task> asyncWriteAction)
    {
      var stream = new MemoryStream();
      var task = asyncWriteAction(stream);
      var result = task.ContinueWith(t =>
      {
        stream.Seek(0, SeekOrigin.Begin);
        return stream.ReadTextToEnd();
      });

      return result;
      
    }
        public static string WriteToString(Action<Stream> writeAction)
    {
      var stream = new MemoryStream();
      writeAction(stream);
      stream.Seek(0, SeekOrigin.Begin);
      return stream.ReadTextToEnd();
    }
        public static string ReadTextToEnd(this Stream stream)
    {
      var reader = new StreamReader(stream);
      var result = reader.ReadToEnd();
      return result;
    }
}

Related Tutorials