【问题标题】:Can't delete image file by its name or path无法按名称或路径删除图像文件
【发布时间】:2018-04-22 18:16:09
【问题描述】:

我正在制作一个 GridView CRUD,它在数据库中保存:RelationFileNameFilePath(全部为 varchar),以及网页内文件夹中的图片。

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

(更新后图片还在)

这是我的代码,没有删除旧图像:

BackEnd(只是更新方法)

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

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

编辑:当我取消注释这些代码行时会发生这种情况:

【问题讨论】:

  • 当我取消注释这些代码行时,我收到一条错误消息,指出这些代码行阻止了对数据库的访问。
  • 你当时正在使用这些图片吗?是否有可能以某种方式将它们作为图像对象加载,从而导致它们被锁定?
  • 我只是使用新的图像,旧的必须删除。当我更新gridview时,新图像出现并且旧图像消失但仍保留在文件夹中而没有任何使用。我想删除那个无用的旧图像,但我不能。
  • 旁注:您似乎依赖用户给定的文件名作为您自己存储的文件名。这可能是个坏主意。您应该自己进行名称管理。用户不能也不应该需要知道您的服务器上已经使用了哪些图像文件名。以国家 ID 命名文件或将其作为 BLOB 存储在数据库中会更安全。
  • “我收到一条错误消息,指出 [取消注释] 这些代码行会阻止访问数据库” - 最好将您遇到的确切错误添加到问题中。我看不出File.Delete 操作会如何干扰数据库——归档系统和数据库是两个独立的东西。

标签: c# mysql asp.net


【解决方案1】:

我已经设法解决了这个问题,我所要做的就是将 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ಥ

【讨论】:

    猜你喜欢
    • 2023-02-02
    • 1970-01-01
    • 1970-01-01
    • 2014-05-21
    • 2016-02-29
    • 1970-01-01
    • 2019-08-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多