2
Answers

Updating image field in SQL 2005

Seth

Seth

16y
2.8k
1

Feel free to move this if it does not belong. I am trying to update an image field in a SQL 2005 database. My code  does not throw and exception but whe I check the database I don't see the image.

We have a directory full of jpg files named a users identifier (person123.jpg)

I loop through the directory and update the database using the file name and the image using the following code. Any ideas? Thanks!

 

public void InsertPictures()

{

DirectoryInfo pictures = new DirectoryInfo(_pathToPictures);

foreach (FileInfo pictureFile in pictures.GetFiles())

{

byte[] photo = GetPhoto(pictureFile.FullName.ToString());

personid = pictureFile.Name.ToString();

personid = stuNum.Replace(".jpg","").Trim();

SqlConnection conn= new SqlConnection(sqlconn);

SqlCommand updatePicture = new SqlCommand("UPDATE PictureTable SET Picture = " +

"@Pic WHERE PersonId = @PersonId" ,conn);

updatePicture.Parameters.Add("@PersonId", SqlDbType.Char, 10).Value = personid;

updatePicture.Parameters.Add("@Pic", SqlDbType.Image, photo.Length).Value = photo;

try

{

conn.Open();

updatePicture.ExecuteNonQuery();

conn.Close();

}

catch (SqlException se)

{

string err = se.Message.ToString();

}

}

}

private byte[] GetPhoto(string filePath)

{

FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);

BinaryReader br = new BinaryReader(fs);

byte[] photo = br.ReadBytes((int)fs.Length);

br.Close();

fs.Close();

return photo;

}

 

 

Answers (2)