2
votes

I am displaying the images of a directory on the site and the user can upload and delete the contents of this folder. However, for some reason my delete link button is not working. Here is my code to display the Images (It works no issues):

{
            string[] filesindirectory = Directory.GetFiles(Server.MapPath("~/Images/Products/"));
            List<String> images = new List<string>(filesindirectory.Count());

            foreach (string item in filesindirectory)
            {
                images.Add(String.Format("~/Images/Products/{0}", System.IO.Path.GetFileName(item)));
            }
            ListView1.DataSource = images;
            ListView1.DataBind();
        }

Here is my code for the Delete Link Button (This is not working):

protected void deleteLinkButton_Click(object sender, EventArgs e)
    {
        var deleteButton = sender as LinkButton;
        string[] filesindirectory = Directory.GetFiles(Server.MapPath("~/Images/Products/{0}"));
        try
        {
            FileInfo fi = new FileInfo(Server.MapPath("~/Images/Products/"));
            fi.Delete();
            statusLabel2.Text = "Delete Image Successful!";
        }
        catch
        {
            // Display error
            statusLabel2.Text = "Delete Image Failed";
        }
        ListView1.DataBind();
    }

When I try to delete a file I am receiving this error: System.IO.DirectoryNotFoundException: Could not find a part of the path

And my stack trace is displaying:

System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) +359 System.IO.FileSystemEnumerableIterator1.CommonInit() +268 System.IO.FileSystemEnumerableIterator1..ctor(String path, String originalUserPath, String searchPattern, SearchOption searchOption, SearchResultHandler`1 resultHandler, Boolean checkHost) +445 System.IO.Directory.GetFiles(String path) +70

2

2 Answers

2
votes

You specify invalid search path "~/Images/Products/{0}" which gives you the error - not sure what it should be.

You are trying to delete directory as file - hence the next error would be on this line:

FileInfo fi = new FileInfo(Server.MapPath("~/Images/Products/"));
fi.Delete()
1
votes
FileInfo fi = new FileInfo(Server.MapPath("~/Images/Products/"));

here you try to initiate a directory as file

string[] filesindirectory = Directory.GetFiles(Server.MapPath("~/Images/Products/{0}"));

and here your have a invalid directory-path - this one throws your exception