Bart88 Bart88 - 1 month ago 6
Vb.net Question

C# open file with variable characters

I have a few files named like:


  1. 6327_1-SWD001-171016_1.txt

  2. 6327_1-SWD011-181016_1.txt

  3. 6327_1-SWD028-191016_1.txt



As you can see th SWD value swaps per file and I would like to know if there is a way to open a file without knowing the SWD value, something like this:

6327_1-SWD???-171016_1.txt

or does a
StreamReader
need the EXACT name of a file?

Answer

StreamReader needs the EXACT name of the file. You can, however, use Directory.GetFiles to find the file you are looking for:

var files = Directory.GetFiles(@"C:\Some\Directory", "6327_1-SWD???-171016_1.txt");  // C#

Dim files = Directory.GetFiles("C:\Some\Directory", "6327_1-SWD???-171016_1.txt")    ' VB

files then contains an array of all file names (including the path) matching your pattern. Directory.GetFiles supports the * and ? wildcards.

(Unrelated side note: Check out File.ReadLines, File.ReadAllLines and File.ReadAllText. Usually, you don't need a StreamReader to read a text file's contents anymore. Note that those methods need the full file name as well.)

Comments