0

I need to search file in directory using partial name.

Ex:

Directory : c:\Path Filename : Error_005296-895632-12563.xml Partial file name: 005296-895632-12563 

I have tried below.

Directory.GetFiles("c:\Path", "*005296-895632-12563*.xml", SearchOption.AllDirectories). 

But it didn't work

Sample file names are :

Error_005296-895632-12563.xml 005296-895632-12563_Response.xml Duplicate_005296-895632-12563_Response.xml 
4
  • stackoverflow.com/questions/8443524/… may help Commented Aug 4, 2017 at 14:03
  • Possible duplicate: stackoverflow.com/questions/1601241/… Commented Aug 4, 2017 at 14:03
  • You don't even need regexes or patterns, just loop over the filenames in the directory and use string.Contains Commented Aug 4, 2017 at 14:08
  • 1
    Answers will differ by language. Please select either c# or vb.net Commented Aug 4, 2017 at 14:50

2 Answers 2

1

You can create a extension method and pass the array of partial names which you want to find.

Call the extension method like this

DirectoryInfo dir = new DirectoryInfo(@"c:\demo"); FileInfo[] files = dir.GetFilesBypartialName("Anc_def_", "ABC_123", "12_qweqweqw_123").ToArray(); 

below is the extension method

public static class DirectoryFindFile { public static IEnumerable<FileInfo> GetFilesBypartialName(this DirectoryInfo dirInfo, params string[] partialFilenames) { if (partialFilenames == null) throw new ArgumentNullException("partialFilenames"); var lstpartialFilenames = new HashSet<string>(partialFilenames, StringComparer.OrdinalIgnoreCase); return dirInfo.EnumerateFiles() .Where(f => lstpartialFilenames.Contains(f.Name)); } public static IEnumerable<FileInfo> GetFilesBypartialFilenamesAllDir(this DirectoryInfo dirInfo, params string[] partialFilenames) { if (partialFilenames == null) throw new ArgumentNullException("partialFilenames"); var lstpartialFilenames = new HashSet<string>(partialFilenames, StringComparer.OrdinalIgnoreCase); return dirInfo.EnumerateFiles("*.*", SearchOption.AllDirectories) .Where(f => lstpartialFilenames.Contains(f.Name)); } } 
Sign up to request clarification or add additional context in comments.

Comments

0

Heres a extension function I've used to search directories

public static IEnumerable<string> GetFiles(string path, string searchPatternExpression = "", SearchOption searchOption = SearchOption.AllDirectories) { Regex reSearchPattern = new Regex(searchPatternExpression); return Directory.EnumerateFiles(path, "*", searchOption).Where(file => reSearchPattern.IsMatch(System.IO.Path.GetExtension(file))); } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.