0

I have a folder location corresponding to the variable "path". In this folder, I have a lot of files, but only one called "common.build.9897ytyt4541". What I want to do is to read the content of this file, so with the following, it's working :

string text = File.ReadAllText(Path.Combine(path, "common.build.9897ytyt4541.js"));

The problem is, that the part between "build" and "js", change at each source code compilation, and I am getting a new hash, so I would like to replace the previous code, to have something working at each build, whatever the hash is, I thought to regex but this is not working :

string text = File.ReadAllText(Path.Combine(path, @"common.build.*.js"));

Thanks in advance for your help

2
  • If this is a console application, you could call it with the new build name as an argument. Set a variable to the argument's value and then pass it to the Path.Combine() Commented Feb 6, 2019 at 16:22
  • 1
    Directory.GetFiles(path, @"common.build.*.js") would list matching files, if your positive there will only be one .First() will return it. Commented Feb 6, 2019 at 16:24

2 Answers 2

2

If you know you'll only find one file you can write something like this (plus error handling):

using System.Linq;
...
var filePath = Directory.GetFiles(path, "common.build.*.js").FirstOrDefault();
string text = File.ReadAllText(filePath);
Sign up to request clarification or add additional context in comments.

2 Comments

Like this solution. I haven't tried this code. I was wondering, what order will the files be in you use GetFiles? Are they ordered in any way? If they were ordered by creation / modified date, you could grab the first one in the array. OR in this "code" case, could you just change it to order them by Creation / Modified Date and then let the FirstOrDefault grab that first file????
From the remarks section of the documentation: "The order of the returned file names is not guaranteed; use the Sort method if a specific sort order is required." Directory.GetFiles returns string[], so if you want special logic you would need to open/get additional information on each file
1

No, you need to use the exact filename with using File.ReadAllText. Instead, you need to search for the file, for this you can use Directory.GetFiles, for example:

var matches = Directory.GetFiles(path, "common.build.*.js");

if(matches.Count() == 0)
{
    //File not found
}
else if(matches.Count() > 1)
{
    //Multiple matches found
}
else
{
    string text = File.ReadAllText(matches[0]);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.