由于比较多人问,问了又问,把我以前的代码共享一下。
using System;
using System.Data;
using System.Data.SqlClient;
using System.IO;
// 下面是从数据库取出图片
try
{
    string getPhoto = @"select photo from gch_Customer_Photo where customerID=1234";
    
    DataSet ds = new DataSet();
    sqlDataAdapter1 = new SqlDataAdapter(getPhoto, sqlConnection1);
    sqlDataAdapter1.Fill(ds);
    DataRow row = ds.Tables[0].Rows[0];
    byte[] bPhoto = new byte[0];
    bPhoto = (byte[])row["photo"];
    //int arraySize = bPhoto.GetUpperBound(0);
    MemoryStream memstr = new MemoryStream(bPhoto);
    pictureBox1.Image = Image.FromStream(memstr, true);
    existPhoto==true
}
catch(Exception ex)
{
    Console.WriteLine(ex.ToString());
}
// 下面是将图片存入数据库
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "*.bmp;*.jpg;*.gif|*.bmp;*.jpg;*.gif;*.jpeg";
if(ofd.ShowDialog()==DialogResult.OK)
{
    string filePath = ofd.FileName;
    FileInfo imageFile = new FileInfo(filePath);
    if(imageFile.Length > 204800)
    {
        Console.WriteLine("图片大小最好不要过大!");
    }
pictureBox1.Image = Image.FromFile(filePath);
    if(existPhoto==true)
    { //如果之前已有图片,可以考虑删除了旧的先
        string deleteOld = @"delete from gch_Customer_Photo where customerID=1234";
        SqlCommand sqlcmmd = new SqlCommand(deleteOld,sqlConnection1);
        sqlcmmd.ExecuteNonQuery();
    }
string getAllPhotos = @"select customerID, photo from gch_Customer_Photo";
    DataSet ds = new DataSet();
    sqlDataAdapter1 = new SqlDataAdapter(getAllPhotos,sqlConnection1);
    sqlDataAdapter1.MissingSchemaAction = MissingSchemaAction.AddWithKey;
FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Read);
    byte[] bPhoto= new byte[fs.Length];
    fs.Read(bPhoto, 0, System.Convert.ToInt32(fs.Length));
    fs.Close();
    sqlDataAdapter1.Fill(ds);
                    
    DataRow oneRow = ds.Tables[0].NewRow();
    oneRow["customerID"] = 1234;
    oneRow["photo"] = bPhoto;
    ds.Tables[0].Rows.Add(oneRow);
    sqlDataAdapter1.Update(ds);
    
    Console.WriteLine("图片入库成功!");
}
[此贴子已经被作者于2006-12-2 13:31:19编辑过]



											

	    

	
 不行,用Message不够ToString好,原因是……