Maciej Stiller
Maciej Stiller

Reputation: 17

Reading specific data from file

I want to read specific data from bat file (set values) and then write them into Textbox1.Text (these are first lines of file I want to read from) and I want to get values

XXXXX write to Textbox1.Text

YYYYY write to Textbox2.Text

ZZZZZ write to Textbox3.Text

SSSSS write to Textbox4.Text

   @echo off


   :::::: DANE LOGOWANIA DO BAZY DANYCH
   :: Baza danych
   set DB=XXXXX
   :: Serwer Bazy danych
   set DBServer=YYYYY
   :: Login do bazy danych
   set DBUser=ZZZZZ
   :: Hasło do bazy danych
   set DBPassword=SSSSS

Reading from file should be triggered from

   private void mssqlbutton_Click(object sender, EventArgs e)
   {

   }

Then if someone change Textbox1.Text value it writes those values into file in the position it previously read from.

I've tried finding for a solution using regex, reading by lines but it doesn't work for me or I don't know at all how to do it.

To be precise, I'm just starting my adventure with C#, I'm not that familiar with it yet, so If you could explain to me as well instead of only providing a code I would be grateful :)

EDIT: Actually it is not that small, whole bat file is like that: http://wklej.to/sCQ6i (I know bat file delete log file at the end but i will handle it)

And AppCode: http://wklej.to/Z5IFd

Where in AppCode DBServerInput.Text was Textbox1.Text DBInput.Text was Textbox2.Text DBUserInput.Text was Textbox3.Text DBPasswordInput was Textbox4.Texte

Upvotes: 0

Views: 728

Answers (3)

Tim Schmelter
Tim Schmelter

Reputation: 460108

So where did you get stuck? However, the first requirement is relative easy:

private void ButtonReadBatch_Click(object sender, EventArgs e)
{
    string[] linesToShowInTextBox = File.ReadLines(@"C:\Temp\batchTest.bat")
        .Select(l => l.Trim())
        .Where(l => l.StartsWith("set ", StringComparison.InvariantCultureIgnoreCase) && l.Contains('='))
        .Select(l => l.Split('=').Last().TrimStart())
        .ToArray();
    TextBox1.Lines = linesToShowInTextBox;
}

The second is more complicated, this should give you an idea. It's tested rudimentarily:

private void ButtonSumbitTextboxChangesToBatch_Click(object sender, EventArgs e)
{
    string[] lines = textBox1.Lines;
    if (lines.Length != 0)
    {
        int matchIndex = 0;
        var lineInfos = File.ReadLines(@"C:\Temp\batchTest.bat")
            .Select(l => l.Trim())
            .Select((line, index) => {
                bool isSetLine = line.StartsWith("set ", StringComparison.InvariantCultureIgnoreCase) && line.Contains('=');
                return new{ 
                    line, index, isSetLine,
                    setIndex = isSetLine ? matchIndex++ : -1 
                };
            });
        string[] newLines = lineInfos
            .Select(x => !x.isSetLine || x.setIndex >= lines.Length 
                ? x.line 
                : string.Format("set {0}={1}",
                    x.line.Split(' ')[1].Split('=')[0].Trim(),
                    lines[x.setIndex]))
            .ToArray();
        File.WriteAllLines(@"C:\Temp\batchTest.bat", newLines);
    }
}

So don't use the TextChanged event but another button, otherwise the event is called on any change which causes undesired effects.

Upvotes: 2

zey
zey

Reputation: 6103

I'm weak in Regular Expression , this code string pattern = @"=(?<after>\w+)"; is to match the word after equal sign = , it's better if some experts show for a better way :D

      string txtBatFile= "<physical path for batfile>";
        if (File.Exists(txtBatFile))
        {
                 StreamReader SR = new StreamReader(txtBatFile);
                 string strFileText= SR.ReadToEnd();
                 SR.Close();
                 SR.Dispose();

        string pattern = @"=(?<after>\w+)";        

      MatchCollection matches = Regex.Matches(strFileText, pattern, RegexOptions.Multiline | RegexOptions.IgnoreCase);

        ArrayList _strList = new ArrayList();
        foreach (Match match in matches)
       {
        _strList.Add(match.Groups["after"].ToString());
       }

        Textbox1.Text = _strList[0].ToString();
        Textbox2.Text = _strList[1].ToString();
        Textbox3.Text = _strList[2].ToString();
        Textbox4.Text = _strList[3].ToString();
        }

Upvotes: 0

Patrik
Patrik

Reputation: 1372

You can use the System.IO.File-class and its static Methods to read data from a file. Especially the Method ReadAllLines should help you. Thus, you can iterate over the lines or use an index to address. foreach and for loops should work. The String-class gives you the tools to deconstruct the data read, think of using the Methods Split or IndexOf. Writing the data back to the file can also be done using the System.IO.File-class. The easiest way should be overwriting the complete file with all you values, since the amount of data is pretty low. Consider using the AppendLine-Method from the System.IO.File-class.

The given MSDN-Links should give you a good starting point for your research. I won't post code since you said you want to go onto the adventure for yourself ;-)

Upvotes: 0

Related Questions