简体   繁体   中英

Search for file and delete it, not knowing the path C#

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);
}

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();
    }
}

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