0

I'd like to make a C# application that reads from a file, looks for a specific string (word). I have no idea how that would go.

My file looks like this:

hostname: localhost

How can I read read the 'localhost' part only?

using (StreamReader sr = File.OpenText(config))
{
    string s = "";
    while ((s = sr.ReadLine()) != null)
    {
        string hostname = s;
        Console.WriteLine(hostname);
    }
}

^(up) Reads everything from a file.

Rand Random
  • 7,300
  • 10
  • 40
  • 88
Luke
  • 3
  • 1
  • 2
    What exaclty are you trying to achieve? Are you trying to decide if the textfile contains the word localhost? Or are you trying to get the hostname, which in this example is localhost? – spersson Dec 20 '17 at 09:12
  • If you're trying to check if the file contains a specific word, iterate through all lines and invoke line.contains(). – Fang Dec 20 '17 at 09:13
  • Have you considered using regex to match and capture? For example: https://regex101.com/r/KsAHO4/1 – Fildor Dec 20 '17 at 09:24
  • @spreson I'm trying to get 'localhost' line.@Fang can you give me an example of that too? – Luke Dec 20 '17 at 09:26
  • @Luke: Check https://stackoverflow.com/questions/6183809/using-streamreader-to-check-if-a-file-contains-a-string – Fang Dec 20 '17 at 09:32
  • Is it reasonable to assume that the file is not too big? Like a config file or something with let's say < 500kB ? – Fildor Dec 20 '17 at 09:36

3 Answers3

1

According to your code, you are storing the file content in string hostname, so now you can split your hostnamelike this:

String[] byParts = hostname.split(':')

byPart[1] will contain 'locahost' <br/>
byPart[0] will contain 'hostname'<br/>


Or if you have situation, where you will always get file with hostname: localhost, then you can use:

hostname.Contains("localhost")


Next you can use if() to compare your logic part.

Hope it helps.

mayank bisht
  • 784
  • 9
  • 19
  • If you any further doubts, feel free to ask :) – mayank bisht Dec 20 '17 at 09:29
  • Thanks for the reply. But I think you didn't understand me very well. I'm looking for getting the 'localhost' word out of it. So let's say I have an account databased on .txt file; username: Luke -> I want only the luke Password: tesd -> I want only the 'testd' word – Luke Dec 20 '17 at 12:27
  • ya, for that also above code will work. You will have both the parts of string in the splitting array. `byPart[1] will contain 'locahost' byPart[0] will contain 'hostname`. So in your given example `username: Luke` byPart[0] will contain 'username` & byPart[1] will contain 'Luke`. – mayank bisht Dec 20 '17 at 13:16
  • Change `String[] byParts = hostname.Split(':');` to `string[] byParts = hostname.Split(':');` and try – mayank bisht Dec 20 '17 at 13:29
  • @mayak Still the same. – Luke Dec 20 '17 at 13:31
  • Working demo, similar to your problem and similar to code that i've posted, `http://rextester.com/VVXWJ78849` – mayank bisht Dec 20 '17 at 14:24
  • Well, I don't have any errors. But I'm still confused with the reader. How should it go? http://rextester.com/ATU30636 – Luke Dec 20 '17 at 15:00
  • I didn't understand your question. please elaborate. Ok I think you are asking something like this http://rextester.com/edit/ATU30636, if not then please elaborate your question. :) – mayank bisht Dec 21 '17 at 05:41
  • Yeah, that is it. Thanks :) – Luke Dec 21 '17 at 13:42
0
using (var sr = File.OpenText(path))
{
    string line;
    while ((line = sr.ReadLine()) != null)
    {
        if (line.Contains("localhost"))
        {
            Console.WriteLine(line);
        }
    }
}

This will read the file line by line, and if the line contains localhost, it will write the line to console. This will of course go through all the lines, you might want to break or do something else after you find the line. Or not, depends on your requirements.

spersson
  • 538
  • 1
  • 8
  • 19
0

This is untested!

The following snippet takes advantage of the capturing group feature of Regex. It will look for a complete match in the current line. If the match is successful, it will print out the captured value.

// Define regex matching your requirement
Regex g = new Regex(@"hostname:\s+(\.+?)"); // Matches "hostname:<whitespaces>SOMETEXT" 
                                            // Capturing SOMETEXT as the first group
using (var sr = File.OpenText(path))
{
    string line;
    while ((line = sr.ReadLine()) != null) // Read line by line
    {
        Match m = g.Match(line);
        if (m.Success)
        {
            // Get value of first capture group in regex
            string v = m.Groups[1].Value;
            // Print Captured value , 
            // (interpolated string format $"{var}" is available in C# 6 and higher)
            Console.WriteLine($"hostname is {v}"); 
            break; // exit loop if value has been found
                   // this makes only sense if there is only one instance
                   // of that line expected in the file.
        }
    }
}
Fildor
  • 14,510
  • 4
  • 35
  • 67