图片或文件保存到数据库

以Winform PictureBox控件为例

if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {

 FileStream fs = new FileStream(openFileDialog1 .FileName ,FileMode.Open ,FileAccess.Read );
                Byte[] myByte = new Byte[fs.Length];
                fs.Read(myByte ,0,myByte.Length );
                 fs.Close();

MemoryStream ms = new MemoryStream(myByte );
                this.img_Photo.Image = Image.FromStream(ms);//用MemoryStream来读取流,在图片控件中显示图片
                objPerson.PER_PHOTO =myByte;//将流保存到数据库对象中、objPerson.PER_PHOTO是定义的一个IMage类型的字段
  }

读取并显示

 MemoryStream ms = new MemoryStream((byte[])objPerson.PER_PHOTO);
              Image img = Image.FromStream(ms,true);//从流中读取
              this.img_Photo.Image = img;

MemoryStream内从流可以参考博客园文档http://www.cnblogs.com/kissdodog/archive/2013/01/20/2868864.html

存储word文件到数据库中并读取

//binaryReader存取到数据库

System.IO.FileStream fs=new System.IO.FileStream(this.txtFilePath.Text.Trim, IO.FileMode.Open);

System.IO.BinaryReader  r=new System.IO.BinaryReader(fs);

r.Close()
fs.Close()

fileContent=r.ReadBytes(fs.Length);//将文件流赋值给数据库对象

//binaryWriter读出文件

content = theAPECTTeamA.APA_CONTENT//得到数据库中内容(二进制)
 Path = Windows.Forms.Application.StartupPath & "\1." & theAPECTTeamA.APA_TYPE//创建一个临时的word文件命名为1.doc

if(dir(Path)!="")

{

   kill(Path);//如果文件存在,删掉文件

}

System.IO.FileStream fs=new System.IO.FileStream(Path, IO.FileMode.OpenOrCreate);//打开并创建文件

System.IO.BinaryWriter(fs);

 r.Write(content)
 r.Close()
 fs.Close()

你可能感兴趣的:(数据库)