user2295457 user2295457 - 5 days ago 5
C# Question

Get value from anywhere in a text file C#

I have a value "md5: [md5 value here]", that appears half way across a line roughly 15 lines into a text file.


File was uploaded successfully, md5: [md5_value_would_be_here]

I have no control over the txt files contents so cant write the value to a new line, then pull it.

In c# how would I go about getting the value of md5: (I know in batch I could use a find and replace, but completely blanked out on how to do it in c#).

Any help appreciated :)

heres what I'm using so far...

var data = File
.Select(x => x.Split('='))
.Where(x => x.Length > 1)
.ToDictionary(x => x[0].Trim(), x => x[1]);

string serverFileMD5 = data["md5"];



The following doesn't reach success,

String data = File.ReadAllText("File.txt");
String pattern = "md5: ([a-zA-Z0-9]*) ";
Regex reg = new Regex(pattern);
Match m = reg.Match(data);
if (m.Success)
Group g = m.Groups[1]; // This should be the hash
Console.WriteLine("value of g: " + g);
serverFileMD5 = g.Value;

Ian Ian

Probably the easiest way to do this is by using Regex. Firstly I'd probably read the entire file into a single string:

String content = File.ReadAllText()

Then you can use something along the following lines:

String pattern = "md5: \[([a-zA-Z0-9]*)\]";
Regex reg = new Regex(pattern);
Match m = reg.Match(content);
if(m.Success) {
    Group g = m.Groups[1]; // This should be the hash
    String hash = g.Value;

This makes the assumption that you're hash contains uppercase characters, lowercase characters and numbers. It works like this:

md5: - literally looks for md5: to start the matching

\[ - looks for an open bracket, the \ is used for escaping

(...) - creates a matching group, the bit that matches in here will be in m.Groups[1] making it easier to access the result.

[a-zA-Z0-9]* - This is the long way to say match any alphabet character or number. Note that the * means match many of these, without this it'd just pickup the first character.

\] - simply look for a close bracket, again being escaped

If you need more information about Regex to help you modify the capture, I'd simply recommend checking out a cheat sheet such as