Created
February 28, 2015 09:12
-
-
Save xl1/9943bf6f1b0b8fa357d0 to your computer and use it in GitHub Desktop.
byte[], string, Stream の相互変換
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.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