您现在的位置: 365建站网 > 365文章 > C#使用MemoryStream类读写内存

C#使用MemoryStream类读写内存

文章来源:365jz.com     点击数:864    更新时间:2018-06-04 21:02   参与评论

MemoryStream和BufferedStream都派生自基类Stream,因此它们有很多共同的属性和方法,但是每一个类都有自己独特的用法。这两个类都是实现对内存进行数据读写的功能,而不是对持久性存储器进行读写。

读写内存-MemoryStream类

MemoryStream类用于向内存而不是磁盘读写数据。MemoryStream封装以无符号字节数组形式存储的数据,该数组在创建MemoryStream对象时被初始化,或者该数组可创建为空数组。可在内存中直接访问这些封装的数据。内存流可降低应用程序中对临时缓冲区和临时文件的需要。

下表列出了MemoryStream类的重要方法:

1、Read():读取MemoryStream流对象,将值写入缓存区。

2、ReadByte():从MemoryStream流中读取一个字节。

3、Write():将值从缓存区写入MemoryStream流对象。

4、WriteByte():从缓存区写入MemoytStream流对象一个字节。

Read方法使用的语法如下:

</>code

  1. mmstream.Read(byte[] buffer,offset,count)


其中mmstream为MemoryStream类的一个流对象,3个参数中,buffer包含指定的字节数组,该数组中,从offset到(offset +count-1)之间的值由当前流中读取的字符替换。Offset是指Buffer中的字节偏移量,从此处开始读取。Count是指最多读取的字节数。Write()方法和Read()方法具有相同的参数类型。


MemoryStream类的使用实例:

</>code

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.IO;  
  6.   
  7. namespace ConsoleApplication1  
  8. {  
  9.     class Program  
  10.     {  
  11.         static void Main()  
  12.         {   
  13.             int count;   
  14.             byte[] byteArray;   
  15.             char[] charArray;  
  16.             UnicodeEncoding uniEncoding = new UnicodeEncoding();  
  17.             // Create the data to write to the stream.  
  18.             byte[] firstString = uniEncoding.GetBytes("一二三四五");   
  19.             byte[] secondString = uniEncoding.GetBytes("上山打老虎");   
  20.             using (MemoryStream memStream = new MemoryStream(100))  
  21.             {   
  22.                 // Write the first string to the stream.  
  23.                 memStream.Write(firstString, 0, firstString.Length);   
  24.   
  25.                 // Write the second string to the stream, byte by byte.  
  26.                 count = 0;  
  27.                 while (count < secondString.Length)   
  28.                 {  
  29.                     memStream.WriteByte(secondString[count++]);   
  30.                 }   
  31.   
  32.                 // Write the stream properties to the console.  
  33.                 Console.WriteLine("Capacity={0},Length={1},Position={2}\n", memStream.Capacity.ToString(), memStream.Length.ToString(), memStream.Position.ToString());  
  34.   
  35.                 // Set the position to the beginning of the stream.  
  36.                 memStream.Seek(0, SeekOrigin.Begin);  
  37.   
  38.                 // Read the first 20 bytes from the stream.  
  39.                 byteArray = new byte[memStream.Length];   
  40.                 count = memStream.Read(byteArray, 0, 20);   
  41.   
  42.                 // Read the remaining bytes, byte by byte.  
  43.                 while (count < memStream.Length)   
  44.                 {   
  45.                     byteArray[count++] = Convert.ToByte(memStream.ReadByte());  
  46.                 }   
  47.   
  48.                 // Decode the byte array into a char array  
  49.                 // and write it to the console.  
  50.                 charArray = new char[uniEncoding.GetCharCount(byteArray, 0, count)];   
  51.                 uniEncoding.GetDecoder().GetChars(byteArray, 0, count, charArray, 0);   
  52.                 Console.WriteLine(charArray); Console.ReadKey();  
  53.             }  
  54.         }  
  55.     }  
  56. }



在这个实例代码中使用了using关键字。注意:

using 关键字有两个主要用途:

1、作为指令,用于为命名空间创建别名或导入其他命名空间中定义的类型。

例如:


using System; 

2、作为语句,用于定义一个范围,在此范围的末尾将释放对象。


using(Connection conn=new Connection(connStr))  

{  

}  

//使用using关键字可及时销毁对象 

MemoryStream.Capacity 属性 取得或设定配置给这个资料流的位元组数目。

MemoryStream.Position 属性 指定当前流的位置。

MemoryStream.Length 属性获取用字节表示的流长度。

SeekOrigin()是一个枚举类,作用设定流的一个参数。

SeekOrigin.Begin我得理解就是文件的最开始,“0”是偏移,表示跳过0个字节。写2就是跳过2个字节。

MemoryStream类通过字节读写数据。本例中定义了写入的字节数组,为了更好的说明Write和WriteByte的异同,在代码中声明了两个byte数组,其中一个数组写入时调用Write方法,通过指定该方法的三个参数实现如何写入。

另一个数组调用了WriteByte方法,每次写入一个字节,所以采用while循环来完成全部字节的写入。写入MemoryStream后,可以检索该流的容量,实际长度,当前流的位置,将这些值输出到控制台。通过观察结果,可以确定写入MemoryStream流是否成功。

调用Read和ReadByte两种方法读取MemoryStream流中的数据,并将其进行Unicode编码后输出到控制台。







读取内存流中的数据


在.NET中,使用抽象基类System.IO.Stream代表流,它提供Read和Write两个方法。由于数据流的有序性,因此流对象还有一个读写指针,为此,Stream类还有一个Seek方法用于移动读写指针。  

字符串与字节数组间的互相转化:


</>code

  1. string str = "内存大小";  
  2. byte[] temp = Encoding.UTF8.GetBytes (str);        // 字符串转化为字节数组  
  3. string s = Encoding.UTF8.GetString (temp);        // 字节数组转化为字符串  
  4. Debug.Log (s);

 

Encoding用法比较简单,如果只是字节和字符的互相转换,GetBytes()和GetChars()这两个方法及它们的重载基本上会满足你所有要求。

GetByteCount()及其重载是得到一个字符串转换成字节时实际的字节个数。

GetCharCount()及其重载是得到一个字节数组转换成字符串的大小。

Decoder.GetChars 方法

Decoder.GetChars (Byte[], Int32, Int32, Char[], Int32)

在派生类中重写时,将指定字节数组的字节序列和内部缓冲区中的任何字节解码到指定的字符数组。

在派生类中重写时,将一个字节序列解码为一组字符。


Java里一个byte取值范围是-128~127, 而C#里一个byte是0~255.

首位不同. 但是底层I/O存储的数据是一样的


FileStream对象的数据来自文件,而MemoryStream对象的数据来自内存缓冲区。这两个类都继承自Stream类。 

MemoryStream的数据来自内存中的一块连续区域,这块区域称为“缓冲区(Buffer)”。可以把缓冲区看成一个数组,每个数组元素可以存放一个字节的数据。

在创建MemoryStream对象时,可以指定缓冲区的大小,并且可以在需要的时候更改。  

</>code

  1. //字节数组  
  2.          byte[] buffer = new byte[600];  
  3.  //填充字节数组  
  4.          private void CreateExampleData()  
  5.          {  
  6.              for(int i=0; i<600; i++)  
  7.              {  
  8.                  //byte类型的数最大不能超过255,用256取模实现  
  9.                   buffer[i] = (byte)(i%256);  
  10.               }              
  11.           }

内存流的基本使用方法:  

</>code

  1.  private void OnTestMemory()  
  2.          {  
  3.              //创建测试数据  
  4.               CreateExampleData();  
  5.                
  6.              //创建内存流对象,初始分配50字节的缓冲区  
  7.               MemoryStream mem = new MemoryStream(50);  
  8.   
  9.              //向内存流中写入字节数组的所有数据  
  10.               mem.Write(buffer,0,buffer.GetLength(0));  
  11.    
  12.               MessageBox.Show("写入数据后的内存流长度:" + mem.Length.ToString());  
  13.               MessageBox.Show("分配给内存流的缓冲区大小:" + mem.Capacity.ToString());  
  14.    
  15.               mem.SetLength(550);  
  16.    
  17.               MessageBox.Show("调用SetLength方法后的内存流长度:" + mem.Length.ToString());  
  18.    
  19.               mem.Capacity = 620;//此值不能小于Length属性  
  20.               MessageBox.Show("调用Capacity方法后缓冲区大小:" + mem.Capacity.ToString());  
  21.    
  22.              //将读写指针移到距流开头10个字节的位置  
  23.               mem.Seek(10,SeekOrigin.Begin);  
  24.               MessageBox.Show(mem.ReadByte().ToString());  
  25.               mem.Close();  
  26.           }

内存流的Length属性代表了其中存放的数据的真实长度,而Capacity属性则代表了分配给内存流的内存空间大小。  

可以使用字节数组创建一个固定大小的MemoryStream,  

 MemoryStream mem = new MemoryStream(buffer);  

这时,无法再设置Capacity属性的大小。  

还可以创建只读的内存流对象。  

 MemoryStream mem = new MemoryStream(buffer,false);  

  

FlieStream用于存取文件。  

创建文件并写入内容:  

</>code

  1.  //创建一个新文件  
  2.               FileStream fsForWrite = new FileStream("test.data",FileMode.Create);  
  3.              try  
  4.              {      
  5.                  //写入一个字节  
  6.                   fsForWrite.WriteByte(100);  
  7.                   CreateExampleData();  
  8.                  //将字节数组写入文件  
  9.                   fsForWrite.Write(buffer,0,buffer.GetLength(0));  
  10.               }  
  11.              catch(Exception ex)  
  12.              {      
  13.                   MessageBox.Show(ex.Message);  
  14.               }  
  15.              finally  
  16.              {  
  17.                  //关闭文件  
  18.                   fsForWrite.Close();  
  19.               }

打开文件并读取内容:  

</>code

  1.  private void ReadFromFile()  
  2.          {  
  3.               FileStream fsForRead = new FileStream("test.data",FileMode.Open);  
  4.              try  
  5.              {  
  6.                  //读入一个字节  
  7.                   MessageBox.Show("文件的第一个字节为:"+fsForRead.ReadByte().ToString());  
  8.                  //读写指针移到距开头10个字节处  
  9.                   fsForRead.Seek(10,SeekOrigin.Begin);  
  10.                  byte[] bs = new byte[10];  
  11.                  //从文件中读取10个字节放到数组bs中  
  12.                   fsForRead.Read(bs,0,10);  
  13.               }  
  14.              catch(Exception ex)  
  15.              {      
  16.                   MessageBox.Show(ex.Message);  
  17.               }  
  18.              finally  
  19.              {  
  20.                   fsForRead.Close();         }  
  21.           }

如果一个程序退出了,但它打开的文件没有被关闭,将导致其他程序无法修改或删除此文件。   



FileStream与MemoryStream间的相互作用:

-----解决方案--------------------

</>code

  1.  FileStream fs = new FileStream(path, FileMode.Open); 
  2.   byte[] data = new byte[fs.Length]; 
  3.   fs.Read(data, 0, data.Length); 
  4.   fs.Close();
  5.   MemoryStream ms = new MemoryStream(data);


------解决方案--------------------

</>code

  1.  ///定义并实例化一个内存流,以存放图片的字节数组。 
  2.  MemoryStream m = new MemoryStream(); 
  3.  ///获得当前路径 
  4.  string strAppPath = AppDomain.CurrentDomain.BaseDirectory; //获得可执行文件的路径。 
  5.  ///获得图片路径  
  6.  string strPath = strAppPath + "img\\default.jpg";  
  7.  ///图片读入FileStream  
  8.  FileStream f = new FileStream(strPath, FileMode.open);  
  9.  ///把FileStream写入MemoryStream  
  10.  m.SetLength(f.Length);  
  11.  f.Read(m.GetBuffer(), 0, (int)f.Length);  
  12.  m.Flush();  
  13.  f.Close();



------解决方案--------------------
          FileStream fs = new FileStream(fileName, FileMode.Open);
           byte[] MyData = new byte[fs.Length];
           fs.Read(MyData, 0, (int)fs.Length);
           fs.Close();
           MemoryStream ms = new MemoryStream(MyData);
------解决方案--------------------
MemoryStream ms = new MemoryStream(File.ReadAllBytes("c:\\1.jpg"));


另外在做BCP项目的时候,没有遇到数据库,全部是从内存取的数据

现提供从内存取数据的方法:,这个是我从网上copy的

因为日本的那个项目,我们用的是c++程序读写共有内存,有一个c++写的dll文件

我们调用那个文件即可.


</>code

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Runtime.InteropServices;
  5. namespace CrazyCoder.ShareMemLib
  6. {
  7. public class ShareMem
  8. {
  9. [DllImport("user32.dll", CharSet = CharSet.Auto)]
  10. public static extern IntPtr SendMessage(IntPtr hWnd, int Msg, int wParam, IntPtr lParam);
  11. [DllImport("Kernel32.dll", CharSet = CharSet.Auto)]
  12. public static extern IntPtr CreateFileMapping(int hFile, IntPtr lpAttributes, uint flProtect, uint dwMaxSizeHi, uint dwMaxSizeLow, string lpName);
  13. [DllImport("Kernel32.dll", CharSet = CharSet.Auto)]
  14. public static extern IntPtr OpenFileMapping(int dwDesiredAccess,[MarshalAs(UnmanagedType.Bool)] bool bInheritHandle,string lpName);
  15. [DllImport("Kernel32.dll", CharSet = CharSet.Auto)]
  16. public static extern IntPtr MapViewOfFile(IntPtr hFileMapping,uint dwDesiredAccess, uint dwFileOffsetHigh, uint dwFileOffsetLow,uint dwNumberOfBytesToMap);
  17. [DllImport("Kernel32.dll", CharSet = CharSet.Auto)]
  18. public static extern bool UnmapViewOfFile(IntPtr pvBaseAddress);
  19. [DllImport("Kernel32.dll", CharSet = CharSet.Auto)]
  20. public static extern bool CloseHandle(IntPtr handle);
  21. [DllImport("kernel32", EntryPoint="GetLastError")]
  22. public static extern int GetLastError ();
  23. const int ERROR_ALREADY_EXISTS = 183;
  24. const int FILE_MAP_COPY = 0x0001;
  25. const int FILE_MAP_WRITE = 0x0002;
  26. const int FILE_MAP_READ = 0x0004;
  27. const int FILE_MAP_ALL_ACCESS = 0x0002 | 0x0004;
  28. const int PAGE_READONLY = 0x02;
  29. const int PAGE_READWRITE = 0x04;
  30. const int PAGE_WRITECOPY = 0x08;
  31. const int PAGE_EXECUTE = 0x10;
  32. const int PAGE_EXECUTE_READ = 0x20;
  33. const int PAGE_EXECUTE_READWRITE = 0x40;
  34. const int SEC_COMMIT = 0x8000000;
  35. const int SEC_IMAGE = 0x1000000;
  36. const int SEC_NOCACHE = 0x10000000;
  37. const int SEC_RESERVE = 0x4000000;
  38. const int INVALID_HANDLE_VALUE = -1;
  39. IntPtr m_hSharedMemoryFile = IntPtr.Zero;
  40. IntPtr m_pwData = IntPtr.Zero;
  41. bool m_bAlreadyExist = false;
  42. bool m_bInit = false;
  43. long m_MemSize=0;
  44. public ShareMem()
  45. {
  46. }
  47. ~ShareMem()
  48. {
  49. Close();
  50. }
  51. /// 
  52. /// 初始化共享内存
  53. /// 
  54. /// 共享内存名称
  55. /// 共享内存大小
  56. /// 
  57. public int Init(string strName, long lngSize)
  58. {
  59. if (lngSize <= 0 || lngSize > 0x00800000) lngSize = 0x00800000;
  60. m_MemSize = lngSize;
  61. if (strName.Length > 0)
  62. {
  63. //创建内存共享体(INVALID_HANDLE_VALUE)
  64. m_hSharedMemoryFile = CreateFileMapping(INVALID_HANDLE_VALUE, IntPtr.Zero, (uint)PAGE_READWRITE, 0, (uint)lngSize, strName);
  65. if (m_hSharedMemoryFile == IntPtr.Zero)
  66. {
  67. m_bAlreadyExist = false;
  68. m_bInit = false;
  69. return 2; //创建共享体失败
  70. }
  71. else
  72. {
  73. if (GetLastError() == ERROR_ALREADY_EXISTS) //已经创建
  74. {
  75. m_bAlreadyExist = true;
  76. }
  77. else //新创建
  78. {
  79. m_bAlreadyExist = false;
  80. }
  81. }
  82. //---------------------------------------
  83. //创建内存映射
  84. m_pwData = MapViewOfFile(m_hSharedMemoryFile, FILE_MAP_WRITE, 0, 0, (uint)lngSize);
  85. if (m_pwData == IntPtr.Zero)
  86. {
  87. m_bInit = false;
  88. CloseHandle(m_hSharedMemoryFile);
  89. return 3; //创建内存映射失败
  90. }
  91. else
  92. {
  93. m_bInit = true;
  94. if (m_bAlreadyExist == false)
  95. {
  96. //初始化
  97. }
  98. }
  99. //----------------------------------------
  100. }
  101. else
  102. {
  103. return 1; //参数错误 
  104. }
  105. return 0; //创建成功
  106. }
  107. /// 
  108. /// 关闭共享内存
  109. /// 
  110. public void Close()
  111. {
  112. if (m_bInit)
  113. {
  114. UnmapViewOfFile(m_pwData);
  115. CloseHandle(m_hSharedMemoryFile);
  116. }
  117. }
  118. /// 
  119. /// 读数据
  120. /// 
  121. /// 数据
  122. /// 起始地址
  123. /// 个数
  124. /// 
  125. public int Read(ref byte[] bytData, int lngAddr, int lngSize)
  126. {
  127. if (lngAddr + lngSize > m_MemSize) return 2; //超出数据区
  128. if (m_bInit)
  129. Marshal.Copy(m_pwData, bytData, lngAddr, lngSize);
  130. }
  131. else
  132. {
  133. return 1; //共享内存未初始化
  134. }
  135. return 0; //读成功
  136. }
  137. /// 
  138. /// 写数据
  139. /// 
  140. /// 数据
  141. /// 起始地址
  142. /// 个数
  143. /// 
  144. public int Write(byte[] bytData, int lngAddr, int lngSize)
  145. {
  146. if (lngAddr + lngSize > m_MemSize) return 2; //超出数据区
  147. if (m_bInit)
  148. {
  149. Marshal.Copy(bytData, lngAddr, m_pwData, lngSize);
  150. }
  151. else
  152. {
  153. return 1; //共享内存未初始化
  154. }
  155. return 0; //写成功
  156. }
  157. }
  158. }
  159. using System;
  160. using System.Collections.Generic;
  161. using System.ComponentModel;
  162. using System.Data;
  163. using System.Drawing;
  164. using System.Text;
  165. using System.Windows.Forms;
  166. using ShareMemLib;
  167. namespace YFShareMem
  168. {
  169. public partial class frmShareMem : Form
  170. {
  171. ShareMem MemDB=new ShareMem();
  172. public frmShareMem()
  173. {
  174. InitializeComponent();
  175. }
  176. private void btnOpen_Click(object sender, EventArgs e)
  177. {
  178. if (MemDB.Init("YFMemTest", 10240) != 0)
  179. {
  180. //初始化失败
  181. MessageBox.Show("初始化失败");
  182. }
  183. else
  184. {
  185. btnOpen.Enabled = false;
  186. chkWrite.Enabled = true;
  187. tmrTime.Enabled = true;
  188. }
  189. }
  190. private void tmrTime_Tick(object sender, EventArgs e)
  191. {
  192. byte[] bytData = new byte[16];
  193. int intRet = MemDB.Read(ref bytData, 0, 16);
  194. lstData.Items.Clear(); 
  195. if (intRet == 0)
  196. {
  197. for (int i = 0; i < 16; i++)
  198. {
  199. lstData.Items.Add(bytData[i].ToString());
  200. }
  201. if (chkWrite.Checked)
  202. {
  203. bytData[0]++;
  204. bytData[1] += 2;
  205. if (bytData[0] > 200) bytData[0] = 0;
  206. if (bytData[1] > 200) bytData[1] = 0;
  207. MemDB.Write(bytData, 0, 16);
  208. }
  209. }
  210. }
  211. }


如对本文有疑问,请提交到交流论坛,广大热心网友会为你解答!! 点击进入论坛

发表评论 (864人查看0条评论)
请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
昵称:
最新评论
------分隔线----------------------------

快速入口

· 365软件
· 杰创官网
· 建站工具
· 网站大全

其它栏目

· 建站教程
· 365学习

业务咨询

· 技术支持
· 服务时间:9:00-18:00
365建站网二维码

Powered by 365建站网 RSS地图 HTML地图

copyright © 2013-2024 版权所有 鄂ICP备17013400号