C# 读二进制的心得 之 binaryreader

原文已修改,,参考
http://hi.baidu.com/forever6164/blog/item/fbba7977e1b1511fb051b985.html
这是我写的一个二进制读写程序,,
我想要测试的是   string str    的值不一样时会有什么结果,,,
当是"ad,sad,as,dasf,我我";时,,,,,提示是这样的
1.ad,sad,as,dasf,我我
2.19
3.15
4.ad,sad,as,dasf,
当是"ad,sad,as,dasf,我我,";时,,,,,提示是这样的
1.ad,sad,as,dasf,我我,
2.20
3.20
4.ad,sad,as,dasf,我我,
您应该看出来我要说什么了,,,,就是,最后一个字符如果是汉字结尾的,,它就不要的...
害我找半天错....

         string SSConfig = Application.StartupPath + "\\s.data";

          //string str = "ad,sad,as,dasf,我我";
          string str = "ad,sad,as,dasf,我我,";
          MessageBox.Show(str);
          byte[] bywr = System.Text.Encoding.Default.GetBytes(str);

          MessageBox.Show(bywr.Length.ToString());

          BinaryWriter bw;
          FileStream fs;
          try
          {
              fs = File.OpenWrite(SSConfig);
              bw = new BinaryWriter(fs);
              bw.Write(bywr);
              bw.Flush();
              bw.Close();
              fs.Close();
          }
          catch (Exception ee)
          {
              bw = null;
              fs = null;
              //FindException(ee.Message);
          }

          //read
          byte[] byrr;

          BinaryReader br1,br2;
          FileStream fs1, fs2;
          try
          {
              fs1 = File.OpenRead(SSConfig);
              br1 = new BinaryReader(fs1);
              //bytemp = br.ReadBytes(620);
              int iItemsDatasLen = 0;
              while (br1.PeekChar() != -1)
              {
                  br1.ReadByte();
                  iItemsDatasLen++;
              }
              br1.Close();
              fs1.Close();//得到长度 会让你吓一跳
              //second read
              fs2 = File.OpenRead(SSConfig);
              br2 = new BinaryReader(fs2);

              byrr = br2.ReadBytes(iItemsDatasLen);//read the bytes,but you will find it may lose something...
              br2.Close();
              fs2.Close();

              MessageBox.Show(iItemsDatasLen.ToString());
              string ReStr = System.Text.Encoding.Default.GetString(byrr);
              MessageBox.Show(ReStr);
          }
          catch (Exception ee)
          {
          }

posted @ 2008-03-27 02:33  以函  阅读(3433)  评论(0编辑  收藏  举报