Skip to content

Instantly share code, notes, and snippets.

@xl1
Created February 28, 2015 09:12
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xl1/9943bf6f1b0b8fa357d0 to your computer and use it in GitHub Desktop.
Save xl1/9943bf6f1b0b8fa357d0 to your computer and use it in GitHub Desktop.
byte[], string, Stream の相互変換
using System;
using System.IO;
using System.Text;
namespace Sample
{
public static class ByteArrayExtension
{
public static string ConvertToString(this byte[] bytes)
{
return Encoding.UTF8.GetString(bytes);
}
public static Stream ToStream(this byte[] bytes)
{
return new MemoryStream(bytes);
}
}
public static class StringExtension
{
public static byte[] ToByteArray(this string str)
{
return Encoding.UTF8.GetBytes(str);
}
public static Stream ToStream(this string str)
{
return str.ToByteArray().ToStream();
}
}
public static class StreamExtension
{
public static byte[] ReadAsByteArray(this Stream stream)
{
using (var ms = new MemoryStream())
{
stream.CopyTo(ms);
return ms.ToArray();
}
}
public static string ReadAsString(this Stream stream)
{
using (var reader = new StreamReader(stream, Encoding.UTF8))
{
return reader.ReadToEnd();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment