Caroline Olivia Caroline Olivia - 2 months ago 7
ASP.NET (C#) Question

How do I delete all image files with same album id?

I have a two tables, one with all the pictures (called billeder, its danish), that have foreign key (in my code called 'album') that tells witch album it belongs to, and then I have the one with albums, with the primary key (alb_id). So i can eval the pictures from an specific album.

I know how to delete a picture, both in the table and in the folder on the server. That works fine.

But I need to know how to delete all of the pictures in the folder at once.

I have this so far:

SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["connectionstring"].ToString());

SqlCommand cmd = new SqlCommand();

cmd.Connection = conn;


cmd.CommandText = "DELETE FROM albums WHERE alb_id = @id";
cmd.Parameters.AddWithValue("@id", id);

conn.Open(); // Open the connection
cmd.ExecuteNonQuery();
conn.Close();

cmd.CommandText = "DELETE FROM billeder WHERE album = @id";
cmd.Parameters.AddWithValue("@id", id);

conn.Open(); // Open the connection
cmd.ExecuteNonQuery();
conn.Close();


The code i have for deleting the file:

File.Delete(Server.MapPath("../fotos/" + image));

Answer

Given that you have the image path in the billeder table you can query them before you delete the rows from the table:

cmd.CommandText = "select imagePath FROM billeder WHERE album = @id";
var result = cmd.ExecuteQuery();

Then loop over the result set deleting each image in turn:

foreach (var image in result) // assuming the result set is a list of strings
{
     File.Delete(Server.MapPath("../fotos/" + image));
}

A better solution would be to put the images into a folder per album (either use the album id or, better still a guid, as the name of the folder, then you can delete the folder with a single call.

Comments