使用数据列表从文件夹中删除图像

时间:2017-08-17 16:19:30

标签: c# asp.net button datalist

我通过从文件夹中获取图像在DataList中显示一些图像。现在,当我单击Datalist中的Delete按钮时,我想删除文件夹中的图像。

我的问题是我无法从以下地址获取文件名:

string fileName = e.CommandArgument.ToString();

我尝试了几种解决方案但没有得到正确的解决方案。

Html标记:

<asp:DataList OnDeleteCommand="gvImages_DeleteCommand" ID="gvImages" RepeatColumns="5" 
              RepeatDirection="Horizontal" GridLines="Horizontal" runat="server" 
              BorderColor="#336699" BorderStyle="Solid" ShowHeader="true">
    <ItemTemplate>
    <center>
        <table>
            <tr>
                <td style="width: 90px; height: 90px">
                    <img id="PICID" runat="server" src='<%# Container.DataItem %>' alt='' 
                         style="height: 100px; width: 100px;" /><br />
                    <asp:Button ID="Delete" Height="22px" CommandName="Delete" 
                                Width="100px" runat="server" Text="Delete Picture" /><br />
                </td>
            </tr>
        </table>
    </center>
    </ItemTemplate>
</asp:DataList>

代码隐藏:

protected void gvImages_DeleteCommand(object source, DataListCommandEventArgs e)
{
    //you can hold filename on Button's  CommandArgument 

    string fileName = e.CommandArgument.ToString();

   // here i can not get the file name to delete it from the folder

    File.Delete(Server.MapPath(fileName));

    FileInfo fInfo;

    fInfo = new FileInfo(fileName);

    fInfo.Delete();

    gvImages.DataBind();
}

1 个答案:

答案 0 :(得分:0)

您必须在DataList中添加asp:Image控件并尝试:

Html标记: FilePath是数据源中的列名。

<asp:Image ID="PICID" runat="server" 
           ImageUrl='<%# DataBinder.Eval(Container.DataItem, "FilePath") %>' />

代码隐藏:gvImages_DeleteCommand事件中:

string url = ((Image)gvImages.Items[e.Item.ItemIdex].FindControl("PICID")).ImageUrl;

string path = Server.MapPath(url);

if (File.Exists(path))
{
    File.Delete(path); // deletes file from folder
}