Created
August 17, 2011 19:13
-
-
Save wcharczuk/1152357 to your computer and use it in GitHub Desktop.
Stream Extensions
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
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.IO; | |
using System.Text; | |
namespace yourNameSpaceHere | |
{ | |
public static class StreamExtensions | |
{ | |
public static int ChunkSize = 32768; | |
/// <summary> | |
/// Gets a string representation of the given stream's data. Uses .net default encoding (unicode) | |
/// </summary> | |
/// <param name="inStream"></param> | |
/// <returns></returns> | |
public static String GetString(this System.IO.Stream inStream) | |
{ | |
string str = string.Empty; | |
using (StreamReader reader = new StreamReader(inStream, str.GetDefaultEncoding())) | |
{ | |
str = reader.ReadToEnd(); | |
} | |
return str; | |
} | |
/// <summary> | |
/// Reads the input stream to the byte[] for saving, also has option to close the stream. | |
/// </summary> | |
/// <param name="inStream">Stream to read.</param> | |
/// <param name="closeStream">Bool to tell the function whether or not to close the stream.</param> | |
public static Byte[] GetBytes(this System.IO.Stream inStream, Boolean closeStream = true) | |
{ | |
inStream.Position = 0; | |
int initialLength = 0; | |
try | |
{ | |
if (inStream.Length != 0) | |
{ | |
initialLength = (int)inStream.Length; | |
} | |
} | |
catch (NotSupportedException e) | |
{ | |
String s = e.ToString(); | |
initialLength = ChunkSize; | |
} | |
byte[] buffer = new byte[initialLength]; | |
int read = 0; | |
int chunk; | |
while ((chunk = inStream.Read(buffer, read, buffer.Length - read)) > 0) | |
{ | |
read += chunk; | |
if (read == buffer.Length) | |
{ | |
int nextByte = inStream.ReadByte(); | |
if (nextByte == -1) | |
{ | |
return buffer; | |
} | |
byte[] newBuffer = new byte[buffer.Length * 2]; | |
Array.Copy(buffer, newBuffer, buffer.Length); | |
newBuffer[read] = (byte)nextByte; | |
buffer = newBuffer; | |
read++; | |
} | |
} | |
byte[] ret = new byte[read]; | |
Array.Copy(buffer, ret, read); | |
if (closeStream) | |
{ | |
inStream.Close(); | |
} | |
return ret; | |
} | |
public const int BUFFER_SIZE = 524000; | |
public static void Pipe(this Stream fromStream, Stream toStream) | |
{ | |
byte[] buffer = new byte[BUFFER_SIZE]; | |
int bytesRead = 0; | |
do | |
{ | |
bytesRead = fromStream.Read(buffer, 0, BUFFER_SIZE); | |
toStream.Write(buffer, 0, bytesRead); | |
} while (bytesRead > 0); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment