Stream流的读取使用


这个是在现在的项目里,用到的知识点,一般用不到这些。。所以想着还是记下来以后用。

针对文本流

//StreamReader sr = new StreamReader(mystream,Encoding.UTF8);
//string logstream = sr.ReadToEnd();

针对图片流

Image.FromStream(stream);

下面的是一个公司项目里的范例是针对文本和图片拼在一起的一个流

 //FileStream用于写入文件
                FileStream fs = new FileStream(imgpath, FileMode.CreateNew);

                BinaryWriter w = new BinaryWriter(fs);
                // 设置要写入的偏移量 
                Stream mystream = wresp.GetResponseStream();
byte[] tempOneByte = new byte[1];
                byte[] temp1024Byte = new byte[1024];

                int readLength = mystream.Read(tempOneByte, 0, 1);
                bool beginSave = false;
                while (readLength != 0)
                {
                    if (tempOneByte[0] == 255 && !beginSave)
                    {
                        mystream.Read(tempOneByte, 0, 1);
                        if (tempOneByte[0] == 216)
                        {
                            int iValue = 255;
                            tempOneByte[0] = (byte)iValue;
                            beginSave = true;
                            fs.Write(tempOneByte, 0, 1);
                            fs.Flush();
                            iValue = 216;
                            tempOneByte[0] = (byte)iValue;
                            fs.Write(tempOneByte, 0, 1);
                            fs.Flush();
                            readLength = mystream.Read(temp1024Byte, 0, 1024);
                            continue;
                        }
                    }
                    writeLength += readLength;
                    if (beginSave)
                    {
                        fs.Write(temp1024Byte, 0, readLength);
                        fs.Flush();
                    }
                    else
                    {
                        byteArray.Add(tempOneByte[0]);
                    }
                    if (beginSave)
                        readLength = mystream.Read(temp1024Byte, 0, 1024);
                    else
                        readLength = mystream.Read(tempOneByte, 0, 1);
                }
                w.Close();
                fs.Close();

                byte[] resultbyte = new byte[byteArray.Count];
                for (int i = 0; i < byteArray.Count; i++)
                {
                    resultbyte[i] = (Byte)byteArray[i];
                }
                System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();
                result = UTF8.GetString(resultbyte);