Sehyn
Sehyn

Reputation: 5

Read specific lines of a text file [C#]

I'am trying to read content of a text file.

And store it in a string.

Example :

Text file contains :

Globalization = "0x000000"
HookWindow = "0x000000"
Blabla = "0x000000"
Etc = "0x000000"

I'd like to store them in a string and be able to retrieve that content in a label for example.

So I can say :

String Globalization = GlobalizationInTheTextFile;

And be able to use label.1.text = Globalization;

Upvotes: 0

Views: 165

Answers (3)

nemanja228
nemanja228

Reputation: 551

string globalizationPrefix = "Globalization = ";
string globalizationLine = File.ReadAllLines(filePath)
    .Where(l => l.StartsWith(globalizationPrefix ))
    .FirstOrDefault();

if(globalizationLine != null)
{
    int index = globalizationPrefix.Length;
    string globalizationValue = globalizationLine.Substring(index);
    label1.Text = globalizationValue;
}

Upvotes: 0

Michał Turczyn
Michał Turczyn

Reputation: 37337

You could use File.ReadAllLines static method to store all lines in string[] array and then use LINQ methods to get one specific line starting with Globalization.

string Globalization = File.ReadAllLines("path")
  .Where(s => s.StartsWith("Globalization"))
  .First().Split('=')[1].Trim().Replace("\"", "");

Upvotes: 0

Tobias Tengler
Tobias Tengler

Reputation: 7454

You could do this:

var dictionary = File.ReadAllLines(yourFilePath)
                    .Select(i => i.Split(new[] { " = \"" }, StringSplitOptions.RemoveEmptyEntries))
                    .ToDictionary(i => i[0], j => j[1].TrimEnd('\"'));

string globalization = dictionary["Globalization"];

Assuming your file is of the structure key = "value" and each Key-Value-Pair is on a new line, this allows you to get any value via dictionary["key"].

Hope this helps!

Upvotes: 3

Related Questions