Click here to Skip to main content
15,885,365 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
I have 3 jpg pictures stored in Server.MapPath("Pictures/"). I need a way to read each jpg picture name then loop each filejpg thru the filestream delete below.
C#
try
            {
                using (FileStream fsSource = new FileStream(Server.MapPath("Pictures/" + filejpg), FileMode.Open, FileAccess.Read))
                {
                    File.Delete(Server.MapPath("Pictures/" + filejpg));
                }
            }
            catch (FileNotFoundException ioEx)
            {
                Label100.Text = "Filestream Delete Old: " + ioEx.ToString();
            }


What I have tried:

I tried just deleting the Pictures folder. This did not work: using (FileStream fsSource = new FileStream(Server.MapPath("Pictures/"), FileMode.Open, FileAccess.Read))
Posted
Updated 12-Jul-17 8:49am
Comments
Richard Deeming 12-Jul-17 14:44pm    
That code is never going to work. You've opened the file, which prevents any other process - including your own! - from deleting it. You then try to delete it whilst keeping it open and locked.

Remove the using (FileStream ... ) line, and just use File.Delete.

If it still doesn't work, update your question and explain the problem you're trying to solve.
teledexterus 12-Jul-17 14:53pm    
Then without filestream just File.Delete("Pictures/" + filepg). I need to be able to read the files in "Pictures/" then loop File.Delete("Pictures/" + filepg)

1 solution

A FileStream is used for reading the contents of a file, not for listing the files in a folder.

You can't delete a file whilst you've got an open FileStream referencing it.

If you're trying to delete all matching files in a specific folder, you need to use Directory.GetFiles[^]:
C#
string folder = Server.MapPath("~/Pictures/");
foreach (string file in Directory.GetFiles(folder, "*.jpg"))
{
    try
    {
        File.Delete(file);
    }
    catch (IOException ex)
    {
        Label100.Text = string.Format("Delete '{0}': {1}", Path.GetFileName(file), ex);
    }
}
 
Share this answer
 
Comments
[no name] 12-Jul-17 15:41pm    
+5

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900