使用RowCommand / RowDeleting事件从文件夹/数据库中删除图像

时间:2012-03-05 15:00:31

标签: c# asp.net

我正在上传图片并将其显示在Gridview。我将图片保存在一个文件夹中,并将名称保存在数据库中。如果我上传了3张图片并且必须删除我选择的图片,我想要。所以我有图片1 2 3.当我选择图片2时,这将被删除..我该怎么办?这是我上传图片的代码:

string filename = Path.GetFileName(fileuploadimages.PostedFile.FileName);
fileuploadimages.SaveAs(Server.MapPath("Images/" + filename));

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["baza_chestionar"].ToString());
con.Open();

SqlCommand cmd = new SqlCommand("Insert into Images(ImageName,ImagePath) values(@ImageName,@ImagePath)", con);
cmd.Parameters.AddWithValue("@ImageName", filename);
cmd.Parameters.AddWithValue("@ImagePath", "Images/" + filename);
cmd.ExecuteNonQuery();

con.Close();
Response.Redirect("~/upload.aspx");

2 个答案:

答案 0 :(得分:2)

要删除文件,请使用System.IO.File.Delete

File.Delete(Path.Combine(path, filename));

其余的实现细节,您如何通知服务器要删除的相应文件,取决于您。

答案 1 :(得分:1)

您可以使用以下GridView的事件来删除图像..

  
      
  1. RowCommand
  2.   
  3. RowDeleting
  4.   

代码背后

protected void grd_RowCommand(object sender, GridViewCommandEventArgs e)
{
    grd.Rows[e.RowIndex].FindControl("Control of the file Name"); 
    //Find control that contains file Name
    if (System.IO.File.Exists("FilePath"))
    {
        File.Delete(Path.Combine("path", "FileName"));
    }
    //Your Delete Code to delete record from database
}

protected void grd_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
    grd.Rows[e.RowIndex].FindControl("Control of the file Name"); 
    //Find control that contains file Name
    if (System.IO.File.Exists("FilePath"))
    {
        File.Delete(Path.Combine("path", "FileName"));
    }
    //Your Delete Code to delete record from database
}

HTML

<asp:GridView ID="grd" runat="server" onrowcommand="grd_RowCommand" 
onrowdeleting="grd_RowDeleting">
    <Columns>
        <asp:TemplateField>
            <ItemTemplate>
                <asp:LinkButton ID="delete" runat="server" Text="Select" CommandName="delete"></asp:LinkButton> 
                <asp:LinkButton ID="deleteRow" runat="server" Text="Select" CommandName="deleteRow"></asp:LinkButton>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

请注意 - 您可以使用RowCommand/RowDeleting个活动......我将使用RowDeleting