简体   繁体   中英

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;

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!

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("\"", "");
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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM