Vaughan Slater
Vaughan Slater

Reputation: 115

Create variables from text file

I want to store variables in a .txt file - like I always see in peoples config.txt files, where it's like:

var_name = ['"test url"']

I've got the code below that opens the file and reads it (at the moment just debugging and displays what's in the file, at the moment just 1 variable)

System.IO.StreamReader myFile = new System.IO.StreamReader("C:\\conf\\config.txt");
string myString = myFile.ReadToEnd();

myFile.Close();

MessageBox.Show(myString);

What's in the file is

file_name="C:\\test.txt"

Now I'd like to be able to use that variable in my functions in my VB form. How do I go about doing this? And also, how can I do multiple; so I can have basically a big list of vars that the form loads at launch?

So for example:

// Opens file and reads all variables
// Saves all variables to form
// Can now use varaible in form, e.g. messageBox.Show(file_name);

I'm new to C#, I imagine it's similar to an include but the include is local instead of part of the project.

Upvotes: 0

Views: 1404

Answers (2)

Romain Lambert
Romain Lambert

Reputation: 56

I store and load data (or variables) with Json Deserialization/ serialization in c#.

Here is Serialiazation: I make an object (postlist which is an object list) that i want to save in a text file That way:

 private void save_file()
    {
        string path = Directory.GetCurrentDirectory() + @"\list.txt";
        string json = JsonConvert.SerializeObject(postlist);
        File.WriteAllText(path, json);
        Application.Exit();
    }

You need to install Newtonsoft.Json: http://www.newtonsoft.com/json .You can do it with the Nuget tool console. Don"t forget to use:

using Newtonsoft.Json;

Here is a way to get all your data from the text file, this is the deserialization:

private void read_file_list()
    {
        string line;

        try
        {
            using (StreamReader sr = new StreamReader("list.txt"))
            {
                line = sr.ReadToEnd();
            }
            JsonSerializerSettings jsonSerializerSettings = new JsonSerializerSettings();
            jsonSerializerSettings.MissingMemberHandling = MissingMemberHandling.Ignore;
            postlist = JsonConvert.DeserializeObject<List<Post>>(line, jsonSerializerSettings);
        }
        catch 
        {
           // catch your exception if you want
        }
    }

And here is how i store all my text in my object list "postlist".

Newtonsoft is very usefull and easy to use, i mostly use it to get data from api's.

This my first answer I hope it will help you.

Upvotes: 0

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

Disclamer: standard practice (i.e. Settings) usually is the best policy, however the question has been asked and can be asnwered:

I suggest using dictionary, e.g.

  Dictionary<String, String> MySettings = File
    .ReadLines(@"C:\conf\config.txt")
    .ToDictionary(line => line.Substring(0, line.IndexOf('=')).Trim(),
                  line => line.Substring(line.IndexOf('=') + 1).Trim().Trim('"'));

  ...

  String testUrl = MySettings[var_name];

However, if you prefer "variables" you can try ExpandoObject:

  dynamic ExpSettings = new ExpandoObject();

  var expandoDic = (IDictionary<string, object>) ExpSettings;

  foreach (var pair in MySettings)
    expandoDic.Add(pair.Key, pair.Value);

  ...

  String testUrl = ExpSettings.var_name;

Upvotes: 1

Related Questions