4

I have a C# asp.net page that has to get username/password info from a text file.

Could someone please tell me how.

The text file looks as follows: (it is actually a lot larger, I just got a few lines)

DATASOURCEFILE=D:\folder\folder
var1= etc
var2= more
var3 = misc
var4 = stuff
USERID = user1
PASSWORD = pwd1

all I need is the UserID and password out of that file.

Thank you for your help,

Steve

Steve
  • 1,028
  • 7
  • 25
  • 42

4 Answers4

13

This would work:

var dic = File.ReadAllLines("test.txt")
              .Select(l => l.Split(new[] { '=' }))
              .ToDictionary( s => s[0].Trim(), s => s[1].Trim());

dic is a dictionary, so you easily extract your values, i.e.:

string myUser = dic["USERID"];
string myPassword = dic["PASSWORD"];
BrokenGlass
  • 158,293
  • 28
  • 286
  • 335
  • 1
    That is sick. I love how you just put my code sample to shame. :) – t3rse Mar 02 '11 at 22:45
  • 1
    Trying to compete on Stackoverflow will do that to you! – BrokenGlass Mar 02 '11 at 23:04
  • Probably should use `File.ReadLines` rather than `File.ReadAllLines`, to avoid problems if the file is really big. – Jim Mischel Mar 02 '11 at 23:36
  • @Jim: if OP's settings file is that big he has other problems - but point taken. In a "real world" application there probably would be some error checking as well, all omitted in this sample (I like your blog btw) – BrokenGlass Mar 02 '11 at 23:38
2

Open the file, split on the newline, split again on the = for each item and then add it to a dictionary.

string contents = String.Empty;
using (FileStream fs = File.Open("path", FileMode.OpenRead))
using (StreamReader reader = new StreamReader(fs))
{
    contents = reader.ReadToEnd();
}

if (contents.Length > 0)
{
    string[] lines = contents.Split(new char[] { '\n' });
    Dictionary<string, string> mysettings = new Dictionary<string, string>();
    foreach (string line in lines)
    {
        string[] keyAndValue = line.Split(new char[] { '=' });
        mysettings.Add(keyAndValue[0].Trim(), keyAndValue[1].Trim());
    }

    string test = mysettings["USERID"]; // example of getting userid
}
t3rse
  • 10,024
  • 11
  • 57
  • 84
0

Dictionary is not needed. Old-fashioned parsing can do more, with less executable code, the same amount of compiled data, and less processing:

public string MyPath1;
public string MyPath2;

...

public void ReadConfig(string sConfigFile)
{
  MyPath1 = MyPath2 = "";  // Clear the external values (in case the file does not set every parameter).

  using (StreamReader sr = new StreamReader(sConfigFile))  // Open the file for reading (and auto-close).
  {
    while (!sr.EndOfStream)
    {
      string sLine = sr.ReadLine().Trim();  // Read the next line. Trim leading and trailing whitespace.

      // Treat lines with NO "=" as comments (ignore; no syntax checking).
      // Treat lines with "=" as the first character as comments too.
      // Treat lines with "=" as the 2nd character or after as parameter lines.
      // Side-benefit: Values containing "=" are processed correctly.

      int i = sLine.IndexOf("=");  // Find the first "=" in the line.
      if (i <= 0) // IF the first "=" in the line is the first character (or not present),
        continue;  // the line is not a parameter line. Ignore it. (Iterate the while.)
      string sParameter = sLine.Remove(i).TrimEnd();  // All before the "=" is the parameter name. Trim whitespace.
      string sValue = sLine.Substring(i + 1).TrimStart();  // All after the "=" is the value. Trim whitespace.

      // Extra characters before a parameter name are usually intended to comment it out. Here, we keep them (with or without whitespace between). That makes an unrecognized parameter name, which is ignored (acts as a comment, as intended).
      // Extra characters after a value are usually intended as comments. Here, we trim them only if whitespace separates. (Parsing contiguous comments is too complex: need delimiter(s) and then a way to escape delimiters (when needed) within values.) Side-drawback: Values cannot contain " ".
      i = sValue.IndexOfAny(new char[] {' ', '\t'});  // Find the first " " or tab in the value.
      if (i > 1) // IF the first " " or tab is the second character or after,
        sValue = sValue.Remove(i);  // All before the " " or tab is the parameter. (Discard the rest.)

      // IF a desired parameter is specified, collect it:
      // (Could detect here if any parameter is set more than once.)
      if (sParameter == "MyPathOne")
        MyPath1 = sValue;
      else if (sParameter == "MyPathTwo")
        MyPath2 = sValue;
      // (Could detect here if an invalid parameter name is specified.)

      // (Could exit the loop here if every parameter has been set.)
    } // end while

  // (Could detect here if the config file set neither parameter or only one parameter.)
  } // end using
}
A876
  • 471
  • 5
  • 8
0

You can use Regular expressions to extract each variable. You can read one line at a time, or the entire file into one string. If the latter, you just look for a newline in the expression.

Regards, Morten

Morten
  • 3,778
  • 2
  • 25
  • 45