c# - 无法按名称或路径删除图像文件

标签 c# mysql asp.net

我正在制作一个 GridView CRUD,它在数据库中保存:RelationFileNameFilePath(所有这些都是 varchar),以及网页内文件夹中的图像。

我已经可以添加、选择和删除,但是当我尝试更新时,麻烦来了。当我尝试更新时,我成功地修改了数据库,因为它只是文本。但是,当上传新图片时,旧图片仍然存在,我想在更新时删除旧图片,以便只有新图片保留在文件/文件夹中“图像”,我应该尝试什么?

enter image description here

(更新后图片还在) enter image description here

这是我的代码,旧图像的非工作删除:

后端(只是更新方法)

protected void gvImages_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
    HttpPostedFile file = ((FileUpload)gvImages.Rows[e.RowIndex].FindControl("FileUpload2")).PostedFile;
    string fileName = Path.GetFileName(file.FileName);

    MySqlConnection con = new MySqlConnection(strConnString);
    string strQuery = "update testingdb.country set Relation=@Relation, FileName=@FileName, FilePath=@FilePath where idcountry=@idcountry";
    MySqlCommand cmd = new MySqlCommand(strQuery);
    //string oldFileName = gvImages.Rows[e.RowIndex].Cells[2].Text;
    if (File.Exists(Server.MapPath("images/") + fileName))
    {
        lblFail.Visible = true;
        lblFail.Text = "Ya existe esta entrada.";
        TextBox1.Text = "";
    }
    else
    {

       //File.Delete(Server.MapPath("images/") + oldFileName);
        //guarda archivos al disco
        file.SaveAs(Server.MapPath("images/" + fileName));

        cmd.Connection = con;
        cmd.Parameters.AddWithValue("@Relation", (gvImages.Rows[e.RowIndex].FindControl("txtRel") as TextBox).Text.Trim());
        cmd.Parameters.AddWithValue("@FileName", fileName);
        cmd.Parameters.AddWithValue("@FilePath", "images/" + fileName);
        cmd.Parameters.AddWithValue("@idcountry", Convert.ToInt32(gvImages.DataKeys[e.RowIndex].Value.ToString()));
        cmd.CommandType = CommandType.Text;
        try
        {
            con.Open();
            cmd.ExecuteNonQuery();
            gvImages.EditIndex = -1;
        }
        catch (Exception ex)
        {
            lblFail.Visible = true;
            lblFail.Text = ex.Message;
        }
        finally
        {
            con.Close();
            con.Dispose();

        }
        this.MostrarImagen();
        lblSuccess.Visible = true;
        lblSuccess.Text = "Exito al editar.";
    }
}

FontEnd(只是 Gridview)

        <asp:Label runat="server" ID="lblSuccess" Text="" ForeColor="Green" Visible="false"></asp:Label> 

        <asp:Label runat="server" ID="lblFail" Text="" ForeColor="Red" Visible="false"></asp:Label> 

        <asp:GridView EmptyDataText="No hay registros en la base de datos!" ID="gvImages" runat="server" DataKeyNames="idcountry" OnRowCommand="gvImages_RowCommand" AutoGenerateColumns="false" OnRowDataBound="gvImages_RowDataBound" Height="300px" OnRowEditing="gvImages_RowEditing" OnRowCancelingEdit="gvImages_RowCancelingEdit" OnRowUpdating="gvImages_RowUpdating">
            <Columns>
                <asp:BoundField DataField="idcountry" HeaderText="ID" ReadOnly="true" />
                <asp:TemplateField HeaderText="Relacion">
                    <ItemTemplate>
                        <asp:Label Text='<%# Eval("Relation") %>' runat="server"></asp:Label>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox runat="server" ID="txtRel" Text='<%# Eval("Relation") %>'></asp:TextBox> />
                    </EditItemTemplate>
                </asp:TemplateField>

                <asp:TemplateField HeaderText="Nombre">
                    <ItemTemplate>
                        <asp:Label ID="lblNombre2" Text='<%# Eval("FileName") %>' runat="server"></asp:Label>
                    </ItemTemplate>

                </asp:TemplateField>

                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:Image ID="Image1" runat="server" ImageUrl='<%# Eval("FilePath") %>' Height="300" Width="300" />
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:FileUpload ID="FileUpload2" runat="server" />
                    </EditItemTemplate>
                </asp:TemplateField>

                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:ImageButton CausesValidation="false" CssClass="btnOPTIONS" runat="server" ImageUrl="~/imgBTN/edit.png" Width="30px" Height="30px" ToolTip="Edit" CommandName="Edit" />
                        <asp:ImageButton CausesValidation="false" runat="server" ImageUrl="~/imgBTN/delete.png" Width="30px" Height="30px" ToolTip="Delete" CommandName="Delete" />
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:ImageButton CausesValidation="false" CssClass="btnOPTIONS" runat="server" ImageUrl="~/imgBTN/save.png" Width="30px" Height="30px" ToolTip="Update" CommandName="Update" />
                        <asp:ImageButton CausesValidation="false" runat="server" ImageUrl="~/imgBTN/cancel.png" Width="30px" Height="30px" ToolTip="Cancel" CommandName="Cancel" />
                    </EditItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>

我试过这段代码,但没有成功(在显示的代码中):

//string oldFileName = gvImages.Rows[e.RowIndex].Cells[2].Text;

//File.Delete(Server.MapPath("images/") + oldFileName);

此外,我的删除方法不会从“图像”文件夹中删除图像,只会从数据库中删除图像。

EDIT: This is what happens when i uncomment those lines of code: enter image description here

最佳答案

我已经设法解决了这个问题,我所要做的就是将 oldFileName 更改为:

    string oldFileName = (gvImages.Rows[e.RowIndex].FindControl("lblNombre2") as Label).Text;

在编辑事件之前选择标签中的数据。

还有:

添加:

string mypath = Server.MapPath("images/") + oldFileName;
        File.SetAttributes(mypath, FileAttributes.Normal);
        File.Delete(mypath);

在连接结束时。

终于……ಥvಥ

关于c# - 无法按名称或路径删除图像文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49969217/

相关文章:

c# - 映射的驱动器在打开的对话框中不可见

c# - 以编程方式确定 .NET WinForms 应用程序是否通过调试器启动

c# - Xamarin 在哪里执行绑定(bind)表达式?

mysql - 无条件全选时昂贵的全表扫描

php - 如何在多个for循环中处理PDO对象

c# - ASP.NET MVC3 : How do I hide fields using Html. DisplayForModel 和 Html.EditorForModel

c# - 软件设计与网络服务设计

c# - 如何防止非移动 View 使用.Net MVC5 中的移动布局?

php - Mysql 计数,如果,否则

javascript - 是否可以使用没有 View 状态和回发的 ASP.NET Web 表单