1

I have some ini file include this string : _DeviceName = #1234. Now I want to get the _DeviceName value that is 1234 but it shows me the full string that is _DeviceName = #1234. I tried this code:

if (File.Exists("inifile.ini"))
{
    if (File.ReadAllText("inifile.ini").Split('\r', '\n').First(st => st.StartsWith("_DeviceName")) != null)
    {
        string s = File.ReadAllText("inifile.ini").Split('\r', '\n').First(st => st.StartsWith("_DeviceName"));

        MessageBox.Show(s);

    }
}
Vivek Jain
  • 3,811
  • 6
  • 30
  • 47
zeinab sh
  • 27
  • 1
  • 6
  • 1
    You're calling `ReadAllText` twice and splitting. Looks like you'd be better off calling `File.ReadAllLines` once. – keyboardP Aug 01 '13 at 15:08
  • 1
    possible duplicate of [Reading/writing an INI file](http://stackoverflow.com/questions/217902/reading-writing-an-ini-file) – Jay Riggs Aug 01 '13 at 15:09
  • possible duplicate of [How to extract a particular value from an INI File using a Regular Expression?](http://stackoverflow.com/questions/1946686/how-to-extract-a-particular-value-from-an-ini-file-using-a-regular-expression) – phillip Aug 01 '13 at 15:17
  • If possible, you should use an INI library, or upgrade to the XML conf files that .Net and most modern frameworks strongly encourage. – ssube Aug 01 '13 at 15:23

4 Answers4

2

You could add another split to get the value out:

if (File.Exists("inifile.ini"))
{
    if (File.ReadAllText("inifile.ini").Split('\r', '\n').First(st => st.StartsWith("_DeviceName")) != null)
    {
        string s = File.ReadAllText("inifile.ini")
                   .Split('\r', '\n').First(st => st.StartsWith("_DeviceName"))
                   .Split('=')[1];
        MessageBox.Show(s);
    }
}
Vivek Jain
  • 3,811
  • 6
  • 30
  • 47
Kenneth
  • 28,294
  • 6
  • 61
  • 84
2

You can use File.ReadAllLines instead. You may want to look at existing ini file readers if you're doing anything more complex but this should work. As a side note, it's not efficient to make two File.ReadAllText calls so quickly; in most cases it's best to just store the result in a variable).

if (File.Exists("inifile.ini"))
{
   string[] allLines = File.ReadAllLines("inifile.ini");
   string deviceLine = allLines.Where(st => st.StartsWith("_DeviceName")).FirstOrDefault();

   if(!String.IsNullOrEmpty(deviceLine))
   {
      string value = deviceLine.Split('=')[1].Trim();
      MessageBox.Show(value);
   }
}
keyboardP
  • 68,824
  • 13
  • 156
  • 205
0

I made an application that implements an INI Reader/Writer. Source code not available just yet, but keep checking back, I will have the source uploaded in a few days ( today is 8/14/13) . This particular INI Reader is CASE SENSITIVE and may need modification for special characters, but so far I have had no problems.

http://sourceforge.net/projects/dungeonchest/

Tim H.
  • 26
  • 5
-1

A dirty way would be to use String.Replace("_DeviceName = #", "")

Matt
  • 136
  • 2
  • 10