文件操作(二進制文件)

 /// <summary>
        /// 將文件轉換爲二進制數據
        /// </summary>
        /// <param name="filename"></param>
        /// <returns></returns>
        private byte[] Getbyte(string filename)
        {
            if (filename.Length < 0) return null;
            else
            {
                //將文件加載入文件流中
                FileStream fs = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.ReadWrite);
                //創建二進制流並將圖片劉讀取爲二進制流
                BinaryReader biny = new BinaryReader(fs);
                //返回二進制數據
                byte[] get = biny.ReadBytes((int)fs.Length);

                biny.Close();
                fs.Close();
                return get;



            }

        }

這裏用圖片作爲簡單測試;

 private void 打開圖片ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog op = new OpenFileDialog();
            op.Filter = "jpg類型文件(*.jpg)|*.jpg|BMP類型文件(*.bmp)|*.bmp";

            if (op.ShowDialog()==DialogResult.OK)
            {
                //打開圖片,獲得文件流,調用方法
                byte[] getby = Getbyte(op.FileName);
                //將文件劉放入緩衝區中
                MemoryStream me = new MemoryStream(getby);
                //加載內存流,顯示圖片
                pictureBox1.Image = Image.FromStream(me);
                me.Dispose();
                me.Close();

            }
        }
發佈了45 篇原創文章 · 獲贊 41 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章