0

Been working on a school project and I'm kinda stuck. I've been trying to write something like this, however it doesn't work. Is there any way to look for a file, delete it, but not knowing the exact path of the file?

var files = new List<string>();
                
foreach (DriveInfo d in DriveInfo.GetDrives().Where(x => x.IsReady == true))
{
    files.AddRange(Directory.GetFiles(d.RootDirectory.FullName, "x.jpg", SearchOption.AllDirectories));
}

if (File.Exists(files)) 
{
    File.Delete(files);
}
uvr
  • 515
  • 4
  • 12
meku977
  • 3
  • 1
  • 4
    `foreach(var file in files)` ? – Sinatr May 04 '21 at 11:16
  • 3
    you can recursively iterate through all directories of a drive, check the filename if it corresponds to the target file name and then delete it. So you need a method that goes through a file list and calls itself when it hits a directory – SirOneOfMany May 04 '21 at 11:16
  • So in short, my teacher is gonna hide few .jpg files, he will give me the name of these, however pc im working on has multiple drives, and he isn't going to give me the exact path name. So the program has to look for every possible drive on pc and delete x.jpg. – meku977 May 04 '21 at 11:20
  • yeah, recursion does the trick here: https://code-maze.com/csharp-basics-recursion/ And System.IO.FileInfo – SirOneOfMany May 04 '21 at 11:26
  • 1
    "doesn't work" is not a good problem description. Do you have compiler errors, runtime exceptions, unexpected results? Please specify with exact error messages – Hans Kesting May 04 '21 at 11:28
  • @MichaelGabbay depends if they want to delete all jpgs or a specific one called x, the question seems to imply the latter – MikeT May 04 '21 at 11:45

1 Answers1

3

your problem is

if (File.Exists(files)) 
{
    File.Delete(files);
}

files is not a file path its a list of them

you need to do

foreach(var file in files)
{
    if (File.Exists(file)) 
    {
        File.Delete(file);
    }
}

A simpler way of doing the same thing would be

var files = from d in DriveInfo.GetDrives()
            where d.IsReady
            from f in d.RootDirectory.EnumerateFiles("x.jpg",SearchOption.AllDirectories)
            select f;

foreach(var file in files)
{
    if (file.Exists) 
    {
        file.Delete();
    }
}
MikeT
  • 5,398
  • 3
  • 27
  • 43
  • It compiled, but apparently it has no right to access Documments and files – meku977 May 04 '21 at 11:46
  • you either need to add a check for access rights or just use try catch to skip folders and files you don't have access to – MikeT May 04 '21 at 11:48
  • here is a similar question https://stackoverflow.com/questions/1281620/checking-for-directory-and-file-write-permissions-in-net – MikeT May 04 '21 at 11:53
  • let's say the x.jpg is located in .../project/images/x.jpg where "..." is drive. Is there anyway to look for files actually knowing the path, but not the exact drive? – meku977 May 04 '21 at 11:54