Reputation: 95
I am working in C# converting MS Batch files to WindowsForms.
I have need to read in a list of key=value lines from text files and convert the key to a variable.
Example text
MailClass=Std
Selectivity=MailNoErrors
MailForeigns=No
ImbType=FS
Postnet=No
I would like to set these as variables to be passed between methods and forms as needed.
string MailClass = "Std";
string Selectivity = "MailNoErrors";
string MailForeign s= "No";
string ImbType = "FS";
string Postnet = "No";
I am thinking of loading them into a List[] array.
Where I am getting is how do I make them actual variables?
Upvotes: 0
Views: 8661
Reputation: 56413
using a Dictionary
would be more appropriate to the task at hand.
An example would be something like this:
Dictionary<string, string> myDictionary = new Dictionary<string, string>(); // make this global
var file = File.ReadAllLines(path);
List<string> TempList = new List<string>(file);
TempList.ForEach((line) =>
{
string[] TempArray = line.Split('=');
myDictionary.Add(TempArray[0], TempArray[1]);
});
After you've done that then you can just access you key/value
pairs from the Dictionary
.
Upvotes: 2
Reputation: 9365
I would take it one step forward and create a class:
public class MyVars {
public string MailClass {get;set;}
public string Selectivity {get;set;}
public string MailForeigns {get;set;}
public string ImbType {get;set;}
public string Postnet {get;set;}
}
And initiailize it from the Dictionary
in the other answer like this:
var myVars = new MyVars {
MailClass = dict["MailClass"],
Selectivity = dict["Selectivity"],
MailForeign = dict["MailForeigns"],
ImbType = dict["ImbType"],
Postnet = dict["Postnet"]
}
Then, you are dealing with strong type entity that can easily be moved around.
You can then have different types as well, for example you might decide that Postnet
is a bool
and maybe another int
var will come along next week.
public class MyVars {
public string MailClass {get;set;}
public string Selectivity {get;set;}
public string MailForeigns {get;set;}
public string ImbType {get;set;}
public bool Postnet {get;set;}
public int SomeNewVar {get;set;}
}
var myVars = new MyVars {
MailClass = dict["MailClass"],
Selectivity = dict["Selectivity"],
MailForeign = dict["MailForeigns"],
ImbType = dict["ImbType"],
Postnet = dict["Postnet"]=="YES",
SomeNewVar = int.Parse(dict["SomeNewVar"])
}
Upvotes: 0
Reputation: 2672
If you want key-value pair in your text file convert to c# property then I think you must use T4 template.
I use T4 Template for database tables to C# class creator, like as entity framework.
https://msdn.microsoft.com/en-us/library/bb126478.aspx
Upvotes: -1