0

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"]);
    }
}
tshepang
  • 12,111
  • 21
  • 91
  • 136
chmodder
  • 184
  • 1
  • 3
  • 17
  • What is the problem you are facing? It seems you are storing the file path inside the database and File.Delete will delete the file from the file system. Do you get any error ? – abhishek Oct 12 '13 at 01:07
  • string path = Server.MapPath("~/upload/originals/" + Request.QueryString["id"].ToString()); Do you see the actual path of the file if you put this in a variable and put a breakpoint and see? – abhishek Oct 12 '13 at 01:14
  • No, i don't get any errors, but the file is only deleted from the database, and not from the directory. I think it is just a path-problem. It is supposed to use the file name stored in the table row _"imgnavn"_ and put it in the **Server.MapPath**, but to me it seems that it just takes the id number instead. I'm not really sure, what it does. – chmodder Oct 12 '13 at 01:18
  • I'm not sure what you mean. Something like this?: `protected void sletBtn_Click(object sender, EventArgs e) { string path = Server.MapPath("~/upload/originals/" + Request.QueryString["id"].ToString()); break;` and then click the button? – chmodder Oct 12 '13 at 01:23
  • Do you really want to do this using a querystring? Querystrings can be modified by the user, and you have no control over what they do. – Tim Sep 17 '14 at 20:23
  • You are right. Didn't think of that at the time. Thanks for pointing it out. – chmodder Sep 17 '14 at 20:37

2 Answers2

0

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.

abhishek
  • 2,975
  • 23
  • 38
  • _File.Delete(Server.MapPath("~/upload/originals/") + Request.QueryString["id"].ToString());_ didn't work. I haven't tried putting it into a variable yet, as I'm not really sure how to do it. Should I delete/mark-out all the code for the button and put your code in instead, and then click the button to see what happens? – chmodder Oct 12 '13 at 01:41
  • BTW. I checked the table row data again, and it does have the file-extension in the name. – chmodder Oct 12 '13 at 01:53
0

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));

        ...
    }

    ...
}
Win
  • 61,100
  • 13
  • 102
  • 181
  • That worked great :) Thanks you very much. I haven't heard about ViewState before, but it sound very useful. I will read some more about it. – chmodder Oct 12 '13 at 02:19