Hi tinman,
The Deleting event is indeed a good place. The e parameter has a Keys property that gives you access to the Id of the picture being deleted. You can then use some LINQ to SQL to find the right picture based on its id, look at the ImageUrl of the property and use that to delete the image from disk. Something like this would work:
Code:
protected void ListView1_ItemDeleting(object sender, ListViewDeleteEventArgs e)
{
try
{
int pictureId = Convert.ToInt32(e.Keys[0]); // get the Id of the Picture being deleted
using (PlanetWroxDataContext myContext = new PlanetWroxDataContext())
{
// Use LINQ to SQL to find the right picture
Picture myPicture = (from p in myContext.Pictures
where p.Id == pictureId
select p).SingleOrDefault();
if (myPicture != null)
{
// Found it; now try to delete it
string imagePath = Server.MapPath(myPicture.ImageUrl);
if (System.IO.File.Exists(imagePath))
{
System.IO.File.Delete(imagePath);
}
}
}
}
catch (Exception ex)
{
// Ooops, something went wrong deleting the picture. Cancel delete from DB as well
e.Cancel = true;
}
}
It's pretty difficult to do this as an atomic transaction as the file system isn't transactional. My implementation comes reasonably close. Only when deleting the images succeeds can the database delete be done.
It's probably better to do this in the Deleted event though. That way you can be sure that the record has been deleted from the database successfully before you attempt to delete the image. It's better to have an image without a database record than the other way around as you could end up with broken images if you can't delete the record from the database. You could check e.Exception in the Deleted event to see if the delete operation has succeeded or not.
This is as "industrial" as it gets without writing a lot of code. If you really need this to be transactional, you could also store the image in the database instead of on disk. That way, it's part of the DB record (or at least related to it) and gets deleted automatically. For pros, cons and a detailed code example, check here:
http://imar.spaanjaars.com/QuickDocId.aspx?quickdoc=414
Hope this helps,
Imar