Csharp:The .dat File using BinaryReader and BinaryWriter Convert to DataTable

 /// <summary>
        /// 添加
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            BinaryWriter binWriter = new BinaryWriter(File.OpenWrite(datfile), Encoding.Unicode);//StreamWriter
            binWriter.Seek(0, SeekOrigin.End);
            num =int.Parse(this.textBox1.Text.Trim());
            strsex = this.textBox2.Text.Trim();
            strname = this.textBox3.Text.Trim();
            creatdate =this.dateTimePicker1.Value;
            binWriter.Write(num);
            binWriter.Write(strsex);
            binWriter.Write(strname);
            binWriter.Write(creatdate.ToShortDateString() + Environment.NewLine);
            binWriter.Flush();
            binWriter.Close();

        }

        /// <summary>
        /// 顯示全部
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {

            //創建文件
            //Write out to binary file
            //if (!File.Exists(datfile))
            //{
            //    FileStream myFile = File.Create(datfile);
            //    myFile.Close();
            //}
            //strsex = "男";
            //num = 124;
            //creatdate = DateTime.Now;
            //strname = "塗聚文geovindu";
            //BinaryWriter binWriter = new BinaryWriter(File.OpenWrite(datfile), Encoding.Unicode);//StreamWriter
            //binWriter.Write(num);
            //binWriter.Write(strsex);
            //binWriter.Write(strname);
            //binWriter.Write(creatdate.ToShortDateString() + Environment.NewLine);
            ////binWriter.Seek(1, SeekOrigin.Begin);
            //strsex = "男";
            //num = 125;
            //creatdate = DateTime.Now;
            //strname = "劉志軍";
            ////BinaryWriter binWriter = new BinaryWriter(File.OpenWrite(datfile));
            //binWriter.Write(num);
            //binWriter.Write(strsex);
            //binWriter.Write(strname);
            //binWriter.Write(creatdate.ToShortDateString() + Environment.NewLine);
            ////binWriter.Seek(2, SeekOrigin.Current);
            //strsex = "女";
            //num = 126;
            //creatdate = DateTime.Now;
            //strname = "孩子";
            ////BinaryWriter binWriter = new BinaryWriter(File.OpenWrite(datfile));
            //binWriter.Write(num);
            //binWriter.Write(strsex);
            //binWriter.Write(strname);
            //binWriter.Write(creatdate.ToShortDateString() + Environment.NewLine);
            ////binWriter.Seek(3, SeekOrigin.Current);
            //binWriter.Flush();
            //binWriter.Close();

            //Read from binary file
            //最一條
            //byte[] bs;
            //using (FileStream fs = new FileStream(datfile, FileMode.Open, FileAccess.Read))
            //{
            //    using (BinaryReader br = new BinaryReader(fs))
            //    {
            //        bs = br.ReadBytes((int)fs.Length);
            //    }
            //}
            //foreach (byte detail in bs)
            //{
            //    Console.WriteLine(detail);
            //}
            dt = null;
            dt = new DataTable();
            dt.Columns.Add("ID", typeof(int));
            dt.Columns.Add("Sex", typeof(string));
            dt.Columns.Add("ReName", typeof(string));
            dt.Columns.Add("CreateTime", typeof(DateTime));

            using (BinaryReader binaryReader = new BinaryReader(File.Open(datfile, FileMode.Open), Encoding.Unicode))
            {

                //binaryReader.BaseStream.Seek(0, SeekOrigin.Begin);
                //1
                //while (true)
                //{
                //    num  = binaryReader.ReadInt32();
                //    strsex = binaryReader.ReadString();
                //    strname = binaryReader.ReadString();
                //    creatdate = DateTime.Parse(binaryReader.ReadString());
                //    //data.Add(k, v);

                //    if (binaryReader.BaseStream.Position == binaryReader.BaseStream.Length)
                //        break;
                //}
                //
                //2
                while (binaryReader.PeekChar() != -1)
                {
                    try
                    {
                        num = binaryReader.ReadInt32();
                        strsex = binaryReader.ReadString();
                        strname = binaryReader.ReadString();
                        creatdate = DateTime.Parse(binaryReader.ReadString());
                        dt.Rows.Add(num, strsex, strname, creatdate);
                    }
                    catch (Exception ex)
                    {
                        ex.Message.ToString();
                        break;
                    }

                }
                binaryReader.Close();
            }

            //BinaryReader binReader = new BinaryReader(File.OpenRead(datfile), Encoding.Unicode);

            //num = binReader.ReadInt32();
            //strsex = binReader.ReadString();
            //strname = binReader.ReadString();
            //creatdate = DateTime.Parse(binReader.ReadString());

            this.textBox1.Text = num.ToString();
            this.textBox2.Text = strsex;
            this.textBox3.Text = strname;
            this.dateTimePicker1.Value = creatdate;
            //binReader.PeekChar();

            //num = binReader.ReadInt32();
            //this.textBox4.Text = num.ToString();
            //binReader.Close();

            this.dataGridView1.DataSource = dt;

        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="FilePath"></param>
        /// <param name="buff"></param>
        public static void WriteBuffer(string FilePath, byte[] buff)
        {
            StreamWriter Writer = File.AppendText(FilePath);
            foreach (byte i in buff)
                Writer.BaseStream.WriteByte(i);
            Writer.Close();
        }
        /// <summary>
        /// 查找
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
            string s = this.textBox4.Text.Trim();
            using (BinaryReader binaryReader = new BinaryReader(File.Open(datfile, FileMode.Open), Encoding.Unicode))
            {
                //binaryReader.BaseStream.Seek(0, SeekOrigin.Begin);
                //1
                //while (true)
                //{
                //    num  = binaryReader.ReadInt32();
                //    strsex = binaryReader.ReadString();
                //    strname = binaryReader.ReadString();
                //    creatdate = DateTime.Parse(binaryReader.ReadString());
                //    //data.Add(k, v);

                //    if (binaryReader.BaseStream.Position == binaryReader.BaseStream.Length)
                //        break;
                //}
                //
                //2
                while (binaryReader.PeekChar() != -1)
                {
                    try
                    {
                        num = binaryReader.ReadInt32();
                        strsex = binaryReader.ReadString();
                        strname = binaryReader.ReadString();
                        creatdate = DateTime.Parse(binaryReader.ReadString());
                        if (strname.Contains(s))
                        {
                            this.label2.Text=binaryReader.BaseStream.Position.ToString();
                            this.label3.Text =(binaryReader.BaseStream.Length-binaryReader.BaseStream.Seek(0, SeekOrigin.Current)).ToString();
                            setCurrent = binaryReader.BaseStream.Seek(0, SeekOrigin.Current);
                            //binaryReader.BaseStream.Seek((binaryReader.BaseStream.Position / 50) * 50, 0);
                            this.textBox1.Text = num.ToString();
                            this.textBox2.Text = strsex;
                            this.textBox3.Text = strname;
                            this.dateTimePicker1.Value = creatdate;
                        }

                    }
                    catch (Exception ex)
                    {
                        ex.Message.ToString();
                        break;
                    }

                }

                binaryReader.Close();
            }
        }
        /// <summary>
        /// 修改,創建
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button4_Click(object sender, EventArgs e)
        {
            #region 創建 塗聚文 20130329

            //if (File.Exists(datfile))
            //{
            //    File.Delete(datfile);
            //}

            //dt = null;
            //dt = new DataTable();
            //dt.Columns.Add("ID", typeof(int));
            //dt.Columns.Add("Sex", typeof(string));
            //dt.Columns.Add("ReName", typeof(string));
            //dt.Columns.Add("CreateTime", typeof(DateTime));
            //dt.Rows.Add(1, "男", "塗聚文", "2013-03-1");
            //dt.Rows.Add(2, "女", "王熙鳳", "2013-03-11");
            //dt.Rows.Add(3, "女", "劉麗", "2013-03-21");
            //dt.Rows.Add(4, "男", "劉海粟", "2013-03-3");
            //dt.Rows.Add(5, "男", "高春輝", "2013-03-5");
            //BinaryWriter binWriter = new BinaryWriter(File.OpenWrite(datfile), Encoding.Unicode);//StreamWriter
            ////binWriter.BaseStream.Seek(0, SeekOrigin.Current);
            //////binWriter.Seek((int)setCurrent, SeekOrigin.Current);//定位有問題
            //foreach (DataRow dr in dt.Rows)
            //{
            //    num=(int)dr["ID"];
            //    strsex =(string) dr["Sex"];
            //    strname = (string)dr["ReName"];
            //    creatdate =(DateTime)dr["CreateTime"];
            //    binWriter.Write(num);
            //    binWriter.Write(strsex);
            //    binWriter.Write(strname);
            //    binWriter.Write(creatdate.ToShortDateString() + Environment.NewLine); //+ Environment.NewLine //加一行,成了現在的行
            //}

            //binWriter.Flush();
            //binWriter.Close();
            #endregion 

            //num = int.Parse(this.textBox1.Text.Trim());
            //strsex = this.textBox2.Text.Trim();
            //strname = this.textBox3.Text.Trim();
            //creatdate = this.dateTimePicker1.Value;
            //binWriter.Write(num);
            //binWriter.Write(strsex);
            //binWriter.Write(strname);
            //binWriter.Write(creatdate.ToShortDateString()); //+ Environment.NewLine //加一行,成了現在的行

            //binWriter.Flush();
            //binWriter.Close();

            //using (BinaryReader binaryReader = new BinaryReader(File.Open(datfile, FileMode.Open), Encoding.Unicode))
            //{
            //    while (binaryReader.PeekChar() != -1)
            //    {
            //        //binaryReader.BaseStream.Seek(setCurrent, SeekOrigin.Begin);
            //        num = binaryReader.ReadInt32();
            //        strsex = binaryReader.ReadString();
            //        strname = binaryReader.ReadString();
            //        creatdate = DateTime.Parse(binaryReader.ReadString());
            //        this.textBox1.Text = num.ToString();
            //        this.textBox2.Text = strsex;
            //        this.textBox3.Text = strname;
            //        this.dateTimePicker1.Value = creatdate;
            //    }
            //}

            #region 修改

            BinaryWriter binWriter = new BinaryWriter(File.OpenWrite(datfile), Encoding.Unicode);//StreamWriter
            binWriter.BaseStream.Position = 0;
            num = 8;// int.Parse(this.textBox1.Text.Trim());
            strsex = "女";// this.textBox2.Text.Trim();
            //strname = this.textBox3.Text.Trim();
            //creatdate = this.dateTimePicker1.Value;
            binWriter.Write(num);
            binWriter.BaseStream.Position = 4;
            binWriter.Write(strsex);
            //binWriter.Write(strname);
            //binWriter.Write(creatdate.ToShortDateString()); //+ Environment.NewLine //加一行,成了現在的行
            binWriter.Flush();
            binWriter.Close();

            #endregion 

            #region 查找數據位置
            cudt = null;
            cudt = new DataTable();
            cudt.Columns.Add("ID", typeof(int));
            cudt.Columns.Add("Position", typeof(int));
            cudt.Columns.Add("Legnth", typeof(int));
            cudt.Columns.Add("Sart", typeof(int));
            cudt.Columns.Add("End", typeof(int));
            cudt.Columns.Add("Name", typeof(string));
            cudt.Columns.Add("Value", typeof(string));

                int pos = 0;
                int row = 0;
                int p = 0;
                int br = 0;
                string s = "";
                int starpos = 0;
                int endpos = 0;
            // 1.
            using (BinaryReader b = new BinaryReader(File.Open(datfile, FileMode.Open, FileAccess.Read),Encoding.Unicode))
            {
                // 2.
                // Position and length variables.

                // 2A.
                // Use BaseStream.
                int length = (int)b.BaseStream.Length;
                int k = 0;
                while (b.PeekChar() != -1)//pos < length
                {

                    try
                    {
                        starpos = (int)b.BaseStream.Position;
                        //
                        num = b.ReadInt32();
                        p = (int)b.BaseStream.Position;
                        endpos = (int)b.BaseStream.Position;
                        pos = p;
                       // b.BaseStream.Seek(pos, SeekOrigin.Current);
                        br = (int)b.BaseStream.Length-p;
                        s = b.GetType().ToString();
                       cudt.Rows.Add(row, pos, br, starpos, endpos, s,num.ToString());//添加第一記錄
                        //第二條記錄
                       starpos = (int)b.BaseStream.Position;
                        strsex = b.ReadString();
                        p = (int)b.BaseStream.Position;
                        endpos = p;
                        pos = p;
                        br = (int)b.BaseStream.Length-p;
                        s = b.GetType().ToString();
                        cudt.Rows.Add(row, pos, br, starpos, endpos, s,strsex);//添加第二條記錄
                        //第三第記錄
                        starpos=(int)b.BaseStream.Position;
                        strname = b.ReadString();
                        p = (int)b.BaseStream.Position;
                        endpos = p;
                        pos = p;
                       // b.BaseStream.Seek(pos, SeekOrigin.Current);
                        br = (int)b.BaseStream.Length - p;
                        s = b.GetType().ToString();
                        cudt.Rows.Add(row, p, br, starpos, endpos, s,strname);//添加第三條記錄 

                        //第四條記錄
                        starpos = (int)b.BaseStream.Position;
                        creatdate = DateTime.Parse(b.ReadString());
                        p = (int)b.BaseStream.Position;
                        endpos = p;
                        pos = p;
                        br = (int)b.BaseStream.Length - p;
                        s = b.GetType().ToString();
                        cudt.Rows.Add(row, p, br, starpos, endpos, s, creatdate);//第四記錄                                

                        k++;
                    }

                    catch (Exception ex)
                    {
                        ex.Message.ToString();
                        break;

                    }

                    // 4.
                    // Advance our position variable.
                    pos += sizeof(int);
                    row++;
                }

                //b.BaseStream.Seek(7, SeekOrigin.Current);
                //string f=b.ReadString();
                //MessageBox.Show(f);
                //指定位顯示
                b.BaseStream.Position = 0;
                MessageBox.Show(b.ReadInt32().ToString());
                b.BaseStream.Position = 4;
                MessageBox.Show(b.ReadString());
                b.BaseStream.Position = 7;
                MessageBox.Show(b.ReadString());
                b.Close();

            }
           this.dataGridView2.DataSource = cudt;
            #endregion 

       }

        /// <summary>
        ///
        /// </summary>
        /// <param name="sectorid"></param>
        /// <returns></returns>
        //public string getclientid(string sectorid)
        //{
        //    try
        //    {
        //        DataSet dsobj = new DataSet();
        //        bllobj = new ConverterClass();
        //        string retclientval = "0";

        //        dsobj = bllobj.BinaryDeSerialize(strDataPath + "\\" + "BinaryClientlocation.dat");
        //        DataRow[] dr = dsobj.Tables[0].Select("client_location_id in(" + locationid + ")");
        //        if (dr.Length > 0)
        //        {
        //            foreach (DataRow drow in dr)
        //            {
        //                retclientval = retclientval + "," + drow["client_id"].ToString();
        //            }
        //        }
        //        return retclientval;
        //    }
        //    catch (Exception ex)
        //    {
        //        ex.Message.ToString();
        //    }
        //}
    }
时间: 2024-11-08 22:03:04

Csharp:The .dat File using BinaryReader and BinaryWriter Convert to DataTable的相关文章

Csharp: read excel file using Open XML SDK 2.5

/// <summary> /// /// </summary> public class SheetNameInfo { private int _sheetId; private string _sheetName; private string _rid; /// <summary> /// /// </summary> public int SheetID { get{return _sheetId;} set{_sheetId= value;} }

csharp create ICS file extension

  string schLocation = "Conference Room 涂聚文约会你"; string schSubject = "Business visit discussion约会"; string schDescription = "Schedule description明天到深圳市福田區車公廟冶金大大廈約會"; System.DateTime schBeginDate = Convert.ToDateTime("2/

csharp read excel file get sheetName list

/// <summary> /// /// 塗聚文 /// 20120803 /// Geovin Du ///找到EXCEL的工作表名称 要考慮打開的文件的進程問題 /// </summary> /// <param name="filename"></param> /// <param name="comboBox2"></param> /// <returns></ret

Csharp: Winform 顏色選擇器 Color convert RGB and RGB convert Color

/// <summary> /// 選擇顏色 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button2_Click(object sender, EventArgs e) { //是否選擇了顏色 if (colorDialog1.ShowDialog(thi

asp.net C# 利用BinaryStream 和 BinaryWriter 对二进制文件进行读写操作

完整代码如下:   引入命名空间: using System.IO;  完整代码:  代码如下 复制代码 namespace BinaryStreamApp  {      class Program      {          static void Main(string[] args)          {              //为文件打开一个二进制写入器              FileStream fs;              fs = new FileStream(

如何清除泄露上网行踪的“index.dat”文件

  index.dat是具有"隐藏"属性的文件,它记录着通过浏览器访问过的网址.访问时间.历史记录等信息.实际上它是一个保存了 cookie.历史记录和IE临时文件中所记录内容的副本 ,即使你在IE中把这些内容都清除了,但index.dat文件中的记录还是存在. 在Windows XP系统中的"Documents and SettingsCookies"."Docum ents and SettingsLocal Settin gsHistoryHisto

用vbs读取index.dat内容的实现代码_vbs

复制代码 代码如下: ' +----------------------------------------------------------------------------+ ' | Contact Info | ' +----------------------------------------------------------------------------+ ' Author: Vengy ' modiy:lcx ' Email : cyber_flash@hotmail.

[20160712]ASM ab_+ASM.dat.txt

[20160712]ASM ab_+ASM.dat.txt --如果你使用asm,在dbs目录下$ORACLE_HOME/dbs目录下存在ab_+ASM.dat的文件. --11GR2在grid的用户. $ strings ab_+ASM.dat GREP_COLOR=01;32 HOSTNAME=xxxxxdg2 TERM=linux SHELL=/bin/bash HISTSIZE=2000 KDE_NO_IPV6=1 TMPDIR=/tmp NLS_LANG=AMERICAN_AMERIC

把握VB.NET中的流(Stream)

stream 当你第一次用VB.NET读写文件的时候,你肯定会发现VB.NET摒弃了传统的文件I/O支持,感觉不习惯.其实,在.NET里面,微软用丰富的"流"对象取代了传统的文件操作,而"流",是一个在Unix里面经常使用的对象.我们可以把流当作一个通道,程序的的数据可以沿着这个通道"流"到各种数据存储机构(比如:文件,字符串,数组,或者其他形式的流等).为什么我们会摒弃用了那么久的IO操作,而代之为流呢?其中很重要的一个原因就是并不是所有的数据