stream、string、byte[] 互轉


最近一個項目中用到,下面直接給出源碼

 //字符串轉流
        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.

 

UpdateConvert Object To Byte Array And Viceversa (serialization) Using BinaryFormatter and MemoryStream


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM