You could use LINQ here to group all files with the same filename, and filter groups with more than one duplicate filename:
var duplicates = Directory
.GetFiles(path)
.GroupBy(f => Path.GetFileNameWithoutExtension(f))
.Where(grp => grp.Count() > 1);
The above uses Directory.GetFiles() to list the files in a directory, Enumerable.GroupBy() to group the files without the extension, which can be extracted with Path.GetFileNameWithoutExtension(). Then you can filter the groups with Enumerable.Where().
Demo:
var duplicates = Directory
.GetFiles(path)
.GroupBy(f => Path.GetFileNameWithoutExtension(f))
.Where(grp => grp.Count() > 1);
foreach (var fileGroup in duplicates)
{
Console.WriteLine($"{fileGroup.Key} : {string.Join(", ", fileGroup.Select(f => Path.GetFileName(f)))}");
}
Output:
Randomfilename : Randomfilename.csv, Randomfilename.txt
If you want to check against a specific filename like in your question:
var duplicates = Directory
.GetFiles(path)
.Where(f => Path.GetFileNameWithoutExtension(f) == "Randomfilename");
if (duplicates.Count() > 1)
{
// We found duplicates
}
Which we can wrap into a method as well:
private static bool FileHasDuplicates(string path, string filename)
{
return Directory
.GetFiles(path)
.Where(f => Path.GetFileNameWithoutExtension(f) == filename)
.Count() > 1;
}
If you want to scan all sub directories of a given directory as well, then you can use Directory.EnumerateFiles():
var duplicates = Directory
.EnumerateFiles(path, "*", SearchOption.AllDirectories)
.GroupBy(f => Path.GetFileNameWithoutExtension(f))
.Where(grp => grp.Count() > 1);