1

I have a text file installer.ini where I have a row who is like : fileExecutable=D:\location. I want to get the text after = and put in a variable. After that I want to use that variable instead of D:\location in code.

    foreach (var txt in lin)
    {
        if (txt.Contains("fileExecutable="))
        {
            var ExeFile = txt.Split('=')[1];
        }
    }
    // The installer itself 
    process.StartInfo.FileName = @"D:\location";                       
    process.StartInfo.Arguments = @"-if C:\temp\installer.ini";
    process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
    process.Start();
    process.WaitForExit();
}

I try to put in the variable ExeFile what I have in text file after fileExecutable=and use that variable in this row: process.StartInfo.FileName = @"D:\location";

venerik
  • 5,766
  • 2
  • 33
  • 43
ben
  • 135
  • 8

1 Answers1

1

The variable ExeFile is declared inside the foreach loop and is therefore not useable after the loop. If you move it outside the loop you can use it after the loop.

var ExeFile = String.Empty;
foreach (var txt in lin)
{
    if (txt.Contains("fileExecutable="))
    {
        ExeFile = txt.Split('=')[1];
    }
}

if (!String.IsNullOrEmpty(ExeFile))
{
   // The installer itself 
   process.StartInfo.FileName = ExeFile;                       
   process.StartInfo.Arguments = @"-if C:\temp\installer.ini";
   process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
   process.Start();
   process.WaitForExit();
}

EDIT Alternative

You can you use a regelar expression on the whole INI-file to skip looping through all lines like so:

using System;
using System.Text.RegularExpressions;

public class Program
{
    public static void Main()
    { 
        // dummy ini for testing.
        var ini = "test\nfileExecutable=D:\\location\ntest";

        var regex = new Regex("^fileExecutable=(.+)$", RegexOptions.Multiline);
        var location = regex.Match(ini).Groups[1];

        Console.WriteLine(location);
    }
}

EDIT Yet another alternative

After editing the title of your question it came to me you might want to read other settings from the ini as well. If so, consider using an INI-reader as discussed here: Reading/writing an INI file

Community
  • 1
  • 1
venerik
  • 5,766
  • 2
  • 33
  • 43