Question

I'm trying to create a delete-page for the user to delete a selected image-files in a photoalbum. I just don't know how to select the database table row "navn" ("name" in english) using an url querystring.

Should I make a new SqlConnection and selectcommand for this line?

I'm not really sure, what to do, as i have just started learning the basics in ASP.NET, C# and SQL.

(I hope the danish entries aren't too confusing. You're welcome to ask if something doesn't make sense.)

I think maybe I should put something after the Request.QueryString to select the "navn"-row in the table.

File.Delete(Server.MapPath("~/upload/originals/" + 
            Request.QueryString["id"].ToString()));

Db table "billeder" ("images" in english):

  • Id [Int]
  • imgnavn [Nvarchar]
  • thumbnavn [Nvarchar]
  • alt [Nvarchar]
  • oprettetDen (date created) [DateTime]
  • redigeretDen (last changed) [DateTime]

Below is the complete code for the aspx-page and code behind file:


("sletBtn" is "delete-button")

sletBilleder.aspx

<%@ Page Title="" Language="C#" MasterPageFile="~/admin/AdminMasterPage.master" AutoEventWireup="true" CodeFile="SletBilleder.aspx.cs" Inherits="admin_SletBilleder" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head2" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder3" Runat="Server">
    <table>   
        <tr>
            <th>
                <label>Billede-ID</label>
            </th>
            <th>
                <label>Billede-navn</label>
            </th>
        </tr>
        <tr>
            <td>
                <asp:Label ID="billedeID" runat="server"></asp:Label>
            </td>
            <td>
                <asp:Label ID="billedenavn" runat="server"></asp:Label>
            </td>
        </tr>
    </table>
    <asp:Label ID="Label_msg" runat="server"></asp:Label>
    <asp:Button ID="sletBtn" runat="server" Text="Slet billedet" 
                OnClick="sletBtn_Click" />
    <asp:Button ID="tilAlbumBtn" runat="server" Text="Gå tilbage" 
                OnClick="tilAlbumBtn_Click" />
</asp:Content>

sletBilleder.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;

public partial class admin_SletBilleder : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Label_msg.Text = "<div class='span6 offset1'><div class='alert alert-success'>Er du sikker på, at du vil slette billedet</div></div>";
        }

        // opret forbindelse til databasen
        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = conn;

        // SQL strengen
        cmd.CommandText = "SELECT * FROM [billeder] WHERE [Id] = @Id";
        cmd.Parameters.Add("@Id", SqlDbType.Int).Value = Request.QueryString["id"];

        //åben for forbindelsen til databasen
        conn.Open();

        SqlDataReader reader = cmd.ExecuteReader();

        if (reader.Read())
        {
            billedeID.Text = reader["Id"].ToString();
            billedenavn.Text = reader["imgnavn"].ToString();
        }

        // Luk for forbindelsen til databasen
        // reader.Close();
        conn.Close();
    }

    protected void sletBtn_Click(object sender, EventArgs e)
    {
        try
        {
            // slet Originalfilen i image/upload/Original/ mappen
            File.Delete(Server.MapPath("~/upload/originals/" + Request.QueryString["id"].ToString()));

            // Slet Thumbsfilen i /Images/Upload/Thumbs/
            File.Delete(Server.MapPath("~/upload/thumbs/" + Request.QueryString["id"].ToString()));

            // Slet Resized_Original i /Images/Upload/Resized_Original/ mappen
            File.Delete(Server.MapPath("~/upload/originalsResized/" + Request.QueryString["id"].ToString()));

            // slet filen i databasen
            SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = conn;
            cmd.CommandText = "DELETE FROM Billeder WHERE Id = @ImageId";
            cmd.Parameters.Add("@ImageId", SqlDbType.Int).Value = Request.QueryString["id"].ToString();
            conn.Open();
            cmd.ExecuteNonQuery();
            conn.Close();

            //Redirect til Galleri
            Response.Redirect("default.aspx");
        }

        catch (Exception)
        {
            Label_msg.Text = "<div class='span6 offset1'><div class='alert alert-success'>Billedet blev desværre <b>ikke</b> slettet</div></div>";

        }
    }

    protected void tilAlbumBtn_Click(object sender, EventArgs e)
    {
        Response.Redirect("visBilleder.aspx?id=" + Request.QueryString["id"]);
    }
}
Was it helpful?

Solution

Problem

You are deleting files with id the following names which do not exist.

  • c:...\upload\originals\123
  • c:...\upload\thumbs\123
  • c:...\upload\originalsResized\123

Solution

You need to delete files with correct file names. I did not test the code, but I hope you get the idea.

The following code will save the file name in the ViewState. Then retrieves that file name from ViewState, once button is clicked.

protected void Page_Load(object sender, EventArgs e)
{
    ....

    if (reader.Read())
    {
        billedeID.Text = reader["Id"].ToString();
        billedenavn.Text = reader["imgnavn"].ToString();
        ViewState["imgnavn"] = reader["imgnavn"].ToString();
    }

    ....
}

protected void sletBtn_Click(object sender, EventArgs e)
{
    try
    {

        string imageName = ViewState["imgnavn"].ToString();    

        // slet Originalfilen i image/upload/Original/ mappen
        File.Delete(Server.MapPath("~/upload/originals/" + imageName));

        // Slet Thumbsfilen i /Images/Upload/Thumbs/
        File.Delete(Server.MapPath("~/upload/thumbs/" + imageName));

        // Slet Resized_Original i /Images/Upload/Resized_Original/ mappen
        File.Delete(Server.MapPath("~/upload/originalsResized/" + imageName));

        ...
    }

    ...
}

OTHER TIPS

Can you try using the code below :

Rather than using

File.Delete(Server.MapPath("~/upload/originals/" + Request.QueryString["id"].ToString()));

Can you use

File.Delete(Server.MapPath("~/upload/originals/") + Request.QueryString["id"].ToString());

If you still face the issue, can you try putting the data into a variable and see if the path is fine. I wonder if you have missed out the file extension or not?

string path = Server.MapPath("~/upload/originals/") + Request.QueryString["id"].ToString();

Put a breakpoint and see the content of path.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top