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!
C#
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;
}
Source Pop10 pointsPosted Jan 8, 2008, 7:08 AM EST
Try this tutorial:
http://blogs.msdn.com/jdixon/articles/495408.aspx called "Storing and reading images from SQL in a ASP.NET details"
I found this by searching sourcepop.com:
http://www.sourcepop.com/GetResults.aspx?q=sqlclient%20update%20image%20field
There are more tutorials there too...one talks about using a Blob instead of images. I think for this you could just pass the image bytes perhaps?
Seth7 pointsPosted Jan 8, 2008, 8:55 AM EST