最近一個項目中用到,下面直接給出源碼
//字符串轉流 public static MemoryStream StringToStream(string s) { // convert string to stream byte[] byteArray = Encoding.Unicode.GetBytes(s); MemoryStream stream = new MemoryStream(byteArray); return stream; } //流轉字符串 public static string StreamToString(Stream stream) { StreamReader reader = new StreamReader(stream); string text = reader.ReadToEnd(); return text; } //字符串轉字節數組 public static Byte[] StringToByteArray(string s) { return Encoding.Unicode.GetBytes(s); } //字節數組轉字符串 public static string ByteArrayToString(Byte[] bytes) { return Encoding.Unicode.GetString(bytes); }
不做過多的解釋,我實現的代碼雖然很簡潔,但是很實用~
當然實現方法很多,下面再給出一種比較簡潔主流的,直接過程化來寫了,如下:
string test = “Testing abc lzq″; // convert string to stream MemoryStream stream = new MemoryStream(); StreamWriter writer = new StreamWriter( stream ); writer.Write( test ); writer.Flush(); // convert stream to string stream.Position = 0; StreamReader reader = new StreamReader( stream ); string text = reader.ReadToEnd();
代碼很簡潔,也許正是你需要的~Maybe it's just what you needed.
Update: Convert Object To Byte Array And Viceversa (serialization) Using BinaryFormatter and MemoryStream