简体   繁体   中英

C# reading variables into static string from text file

I have seen several posts giving examples of how to read from text files, and examples on how to make a string 'public' (static or const), but I haven't been able to combine the two inside a 'function' in a way that is making sense to me.

I have a text file called 'MyConfig.txt'. In that, I have 2 lines.

 MyPathOne=C:\TestOne
 MyPathTwo=C:\TestTwo

I want to be able to read that file when I start the form, making both MyPathOne and MyPathTwo accessible from anywhere inside the form, using something like this :

ReadConfig("MyConfig.txt");

the way I am trying to do that now, which is not working, is this :

public voice ReadConfig(string txtFile)
{
    using (StreamReader sr = new StreamResder(txtFile))
    {
        string line;
        while ((line = sr.ReadLine()) !=null)
        {
            var dict = File.ReadAllLines(txtFile)
                           .Select(l => l.Split(new[] { '=' }))
                           .ToDictionary( s => s[0].Trim(), s => s[1].Trim());
        }
        public const string MyPath1 = dic["MyPathOne"];
        public const string MyPath2 = dic["MyPathTwo"];
    }
}

The txt file will probably never grow over 5 or 6 lines, and I am not stuck on using StreamReader or dictionary.

As long as I can access the path variables by name from anywhere, and it doesn't add like 400 lines of code or something , then I am OK with doing whatever would be best, safest, fastest, easiest.

I have read many posts where people say the data should stored in XML, but I figure that part really doesn't matter so much because reading the file and getting the variables part would be almost the same either way. That aside, I would rather be able to use a plain txt file that somebody (end user) could edit without having to understand XML. (which means of course lots of checks for blank lines, does the path exist, etc...I am OK with doing that part, just wanna get this part working first).

I have read about different ways using ReadAllLines into an array, and some say to create a new separate 'class' file (which I don't really understand yet..but working on it). Mainly I want to find a 'stable' way to do this. (project is using .Net4 and Linq by the way)

Thanks!!

You need to define the variables outside the function to make them accessible to other functions.

public string MyPath1; // (Put these at the top of the class.)
public string MyPath2;

public voice ReadConfig(string txtFile)
{
    var dict = File.ReadAllLines(txtFile)
                   .Select(l => l.Split(new[] { '=' }))
                   .ToDictionary( s => s[0].Trim(), s => s[1].Trim());  // read the entire file into a dictionary.

    MyPath1 = dict["MyPathOne"];
    MyPath2 = dict["MyPathTwo"];
}

The code you've provided doesn't even compile. Instead, you could try this:

public string MyPath1;
public string MyPath2;

public void ReadConfig(string txtFile)
{
    using (StreamReader sr = new StreamReader(txtFile))
    {
        // Declare the dictionary outside the loop:
        var dict = new Dictionary<string, string>();

        // (This loop reads every line until EOF or the first blank line.)
        string line;
        while (!string.IsNullOrEmpty((line = sr.ReadLine())))
        {
            // Split each line around '=':
            var tmp = line.Split(new[] { '=' }, 
                                 StringSplitOptions.RemoveEmptyEntries);
            // Add the key-value pair to the dictionary:
            dict[tmp[0]] = dict[tmp[1]];
        }

        // Assign the values that you need:
        MyPath1 = dict["MyPathOne"];
        MyPath2 = dict["MyPathTwo"];
    }
}

To take into account:

  1. You can't declare public fields into methods.

  2. You can't initialize const fields at run-time. Instead you provide a constant value for them at compilation time.

Got it. Thanks!

            public static string Path1;
            public static string Path2;
            public static string Path3;

            public void ReadConfig(string txtFile)
            {
                using (StreamReader sr = new StreamReader(txtFile))
                {
                var dict = new Dictionary<string, string>();
                string line;
                while (!string.IsNullOrEmpty((line = sr.ReadLine())))
                {
                            dict = File.ReadAllLines(txtFile)
                           .Select(l => l.Split(new[] { '=' }))
                           .ToDictionary( s => s[0].Trim(), s => s[1].Trim());
                }
                Path1 = dict["PathOne"];
                Path2 = dict["PathTwo"];
                Path3 = Path1 + @"\Test";
                }
            }

This question is similar to Get parameters out of text file

(I put an answer there. I "can't" paste it here.)

(Unsure whether I should "flag" this question as duplicate. "Flagging" "closes".)

(Do duplicate questions ever get consolidated? Each can have virtues in the wording of the [often lame] question or the [underreaching and overreaching] answers. A consolidated version could have the best of all, but consolidation is rarely trivial.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM