Reputation: 3
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);
}
Upvotes: 0
Views: 168
Reputation: 5500
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();
}
}
Upvotes: 3