Created
January 9, 2015 16:03
-
-
Save feanz/90f99be706cdd8e7a0d7 to your computer and use it in GitHub Desktop.
Stream extension methods
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static Stream ToStream(this string str) | |
{ | |
byte[] byteArray = Encoding.UTF8.GetBytes(str); | |
//byte[] byteArray = Encoding.ASCII.GetBytes(str); | |
return new MemoryStream(byteArray); | |
} | |
public static string ToString(this Stream stream) | |
{ | |
var reader = new StreamReader(stream); | |
return reader.ReadToEnd(); | |
} | |
/// <summary> | |
/// Copy from one stream to another. | |
/// Example: | |
/// using(var stream = response.GetResponseStream()) | |
/// using(var ms = new MemoryStream()) | |
/// { | |
/// stream.CopyTo(ms); | |
/// // Do something with copied data | |
/// } | |
/// </summary> | |
/// <param name="fromStream">From stream.</param> | |
/// <param name="toStream">To stream.</param> | |
public static void CopyTo(this Stream fromStream, Stream toStream) | |
{ | |
if (fromStream == null) | |
throw new ArgumentNullException("fromStream"); | |
if (toStream == null) | |
throw new ArgumentNullException("toStream"); | |
var bytes = new byte[8092]; | |
int dataRead; | |
while ((dataRead = fromStream.Read(bytes, 0, bytes.Length)) > 0) | |
toStream.Write(bytes, 0, dataRead); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment