简体   繁体   中英

How to delete an image from datalist from a local folder with asp.net - Error (system.io.directorynotfoundexception could not find a part of the path)

Appreciate your help with this code, I simply want to add a delete button with C# to remove an image from dataList, I'm new to this and I don't know where to go, this is the code.

  <asp:DataList ID="imgList" repeatColumns="3" runat="server" CssClass="auto-style1" Width="681px"> <ItemTemplate> <asp:Image ID="img1" runat="server" ImageUrl='<%# Bind("Name", "~/images/{0}") %>' width="200px" Height="200px" /> <asp:Button Text="Delete" id="deleteButton" runat="server" OnClick="Delete_Command" /> </ItemTemplate> </asp:DataList> -------------------------------- protected void Delete_Command (object sender, EventArgs e) { string fileName = e.CommandArgument.ToString(); File.Delete(Server.MapPath(fileName)); FileInfo fInfo; fInfo = new FileInfo(fileName); fInfo.Delete(); imgList.DataBind(); } 

the issue has been solved with the help of John, now I have another issue I appreciate any help with it as well

  <asp:DataList ID="imgList" repeatColumns="3" runat="server" CssClass="auto-style1" Width="681px"> <ItemTemplate > <asp:Image ID="img1" runat="server" ImageUrl='<%# Bind("Name", "~/images/{0}") %>' width="200px" Height="200px" /> <asp:Button Text="Delete" ID="deleteButton" OnCommand="Unnamed1_Command" commandArgument='<%# Bind("Name", "~/images/{0}") %>' runat="server" /> </ItemTemplate> </asp:DataList> protected void Unnamed1_Command(object sender, CommandEventArgs e) { string fileName = e.CommandArgument.ToString(); File.Delete(Server.MapPath(fileName)); FileInfo fInfo; fInfo = new FileInfo(fileName); fInfo.Delete(); imgList.DataBind(); } 

I face the error system.io.directorynotfoundexception could not find a part of the path at " fInfo.Delete();" I have no idea why, I tried a few solutions online but nothing works so far with me.

I found the answer after multiple times of checking and code is finally working, I will share, if anyone has something to add to make it better, please do write it down:

  protected void Unnamed1_Command(object sender, CommandEventArgs e) { FileInfo fInfo = new FileInfo (Server.MapPath(e.CommandArgument.ToString())); fInfo.Delete(); imgList.DataBind(); } <asp:DataList ID="imgList" repeatColumns="3" runat="server" CssClass="auto-style1" Width="681px"> <ItemTemplate > <asp:Image ID="img1" runat="server" ImageUrl='<%# Bind("Name", "~/images/{0}") %>' width="200px" Height="200px" /> <asp:Button Text="Delete" ID="deleteButton" OnCommand="Unnamed1_Command" commandArgument='<%# Bind("Name", "~/images/{0}") %>' runat="server" /> </ItemTemplate> </asp:DataList> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM