Filepath not found outside WPF window ctor - c#

I am using following world heatmap in my WPF application:
https://lvcharts.net/App/examples/v1/wpf/GeoHeatMap
//Geomap
private static string GEOMAP_PATH = System.IO.Path.GetDirectoryName(System.AppDomain.CurrentDomain.BaseDirectory) + "\\Materials\\GeoMaps\\World.xml";
public MainMaterialWindow()
{
//Default application initialization
InitializeComponent();
//geomap chart
var values = new Dictionary<string, double>();
foreach (actual_headmapdata data in GetWorldHeadmapData())
{
values[data.isocode] = data.count;
}
geoMap1.HeatMap = values;
var lang = new Dictionary<string, string>();
lang["DE"] = "Germany"; // change the language if necessary
geoMap1.LanguagePack = lang;
geoMap1.Source = GEOMAP_PATH;
}
What I don't understand is why the filepath is not found if I do something like this.
//Geomap
private static string GEOMAP_PATH = System.IO.Path.GetDirectoryName(System.AppDomain.CurrentDomain.BaseDirectory) + "\\Materials\\GeoMaps\\World.xml";
public MainMaterialWindow()
{
//Default application initialization
InitializeComponent();
//init GeoMap
initGeoMap();
}
public void initGeoMap() {
//geomap chart
var values = new Dictionary<string, double>();
foreach (actual_headmapdata data in GetWorldHeadmapData())
{
values[data.isocode] = data.count;
}
geoMap1.HeatMap = values;
var lang = new Dictionary<string, string>();
lang["DE"] = "Germany"; // change the language if necessary
geoMap1.LanguagePack = lang;
geoMap1.Source = GEOMAP_PATH;
}
I get: System.IO.FileNotFoundException: "This file was not found."
So the problem is, why the filepath is not valid anymore once the initialization of the geomap is outside of MainMaterialWindow(). File still exits.
XAML:
<lvc:GeoMap x:Name="geoMap1" HeatMap="{Binding Values}" LanguagePack="{Binding LanguagePack}" Margin="10,0,-12,22" />
Same happens with full filepath as string: GEOMAP_PATH="D:\\Dev\\projectname\\bin\\debug\\Materials\\GeoMaps\\World.xml"
This also only works within MainMaterialWindow(), so it is not about:
private static string GEOMAP_PATH = System.IO.Path.GetDirectoryName(System.AppDomain.CurrentDomain.BaseDirectory)

Related

List to Dictionary and back again

I have read many posts about dictionaries and serialization etc. and they all have different ways of doing things.
Being new to coding (to an extent) I am having trouble figuring out how to get my dictionary to a list or serialized to get it saved then reloaded on play. This is Unity BTW.
So here is what I am using.
I have an application manager that is mainly just a set of BOOL values that tells my mission system if something has been completed or not. Something like "GetWeapon FALSE" (then when they pick it up it changes to TRUE which tells the mission system to move to the next objective or complete)
So I have a starting list of keys,values...these then get placed into a dictionary and the values are changed within that.
I need to be able to save those values and reload them on LOAD (default PLAY mode is newgame--as you see below it resets the dictionary and copies in the starting states). I know it can't be as difficult as I am making it, just not understanding the whole serialize thing.
Most sites are showing a dictionary like {key,value} so I am getting lost on iterating through the dictionary and capturing the pairs and saving them.
Here is partial code for the appmanager (it is a singleton):
// This holds any states you wish set at game startup
[SerializeField] private List<GameState> _startingGameStates = new List<GameState>();
// Used to store the key/values pairs in the above list in a more efficient dictionary
private Dictionary<string, string> _gameStateDictionary = new Dictionary<string, string>();
void Awake()
{
// This object must live for the entire application
DontDestroyOnLoad(gameObject);
ResetGameStates();
}
void ResetGameStates()
{
_gameStateDictionary.Clear();
// Copy starting game states into game state dictionary
for (int i = 0; i < _startingGameStates.Count; i++)
{
GameState gs = _startingGameStates[i];
_gameStateDictionary[gs.Key] = gs.Value;
}
OnStateChanged.Invoke();
}
public GameState GetStartingGameState(string key)
{
for (int i = 0; i < _startingGameStates.Count; i++)
{
if (_startingGameStates[i] != null && _startingGameStates[i].Key.Equals(key))
return _startingGameStates[i];
}
return null;
}
// Name : SetGameState
// Desc : Sets a Game State
public bool SetGameState(string key, string value)
{
if (key == null || value == null) return false;
_gameStateDictionary[key] = value;
OnStateChanged.Invoke();
return true;
}
Tried something similar to this:
Dictionary<string, string> _gameStateDictionary = new Dictionary<string, string>
{
for (int i = 0; i < _gameStateDictionary.Count; i++)
string json = JsonConvert.SerializeObject(_gameStateDictionary, Formatting.Indented);
Debug.Log(json);
{
}
However all I got was the first item in the list. (I did modify the above in a for loop) I know the above is wrong, I did other iterations to just to get the dictionary to print out in the console.
Anyway, just asking for a little code help to save and load a dictionary.
Since you want to save and load those persistent anyway, personally I would not use the Inspector and bother with Unity serialization at all but rather directly serialize/deserialize from and to json.
Simply place your default dictionary as a simple json file like e.g.
{
"Key1" : "Value1",
"Key2" : "Value2",
"Key3" : "Value3",
...
}
within the folder Assets/StreamingAssets (create it if it doesn't exists). This will be your default fallback file if none exists so far.
On runtime you will load it from Application.streamingAssetsPath.
Then when saving you will not put it there but rather to the Application.persistentDataPath
using Newtonsoft.Json;
...
[SerializeField] private string fileName = "example.json";
private string defaultStatesPath => Path.Combine(Application.streamingAssetsPath, fileName);
private string persistentStatesPath => Path.Combine(Application.persistentDataPath, fileName);
private Dictionary<string, string> _gameStateDictionary
public void Load()
{
var filePath = persistentStatesPath;
if(!File.Exists(filePath))
{
filePath = defaultStatesPath;
}
var json = File.ReadAllText(filePath);
_gameStateDictionary = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
}
public void Save()
{
var filePath = persistentStatesPath;
if(!Directory.Exists(Application.persistentDataPath))
{
Directory.CreateDirectory(Application.persistentDataPath);
}
var json = JsonConvert.SerializeObject(_gameStateDictionary, Formatting.intended);
File.WriteAllText(filePath, json);
}
If you then still want to edit the default via the Inspector you could merge both and instead of using StreamingAssets do
[SerializeField] private GameState[] defaultStates;
public void Load()
{
var filePath = persistentStatesPath;
if(!File.Exists(filePath))
{
LoadDefaults();
return;
}
var json = File.ReadAllText(filePath);
_gameStateDictionary = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
}
public void LoadDefaults()
{
_gameStateDictionary = defaultStates.ToDictionary(gameState => gameState.Key, gameState => gameState.Value);
}
And then btw you could do
public string GetState(string key, string fallbackValue = "")
{
if(_gameStateDictionary.TryGetValue(key, out var value))
{
return value;
}
return fallbackValue;
}
You can iterate the dictionary by using its Keys collection.
foreach (var key in myDictionary.Keys)
{
var val = myDictionary[key];
}
Populate your data structure with the key/value pairs and serialize the list of items.
var missionItems = new List<MissionItem>();
foreach (var key in myDictionary.Keys)
{
var missionItem = new MissionItem();
missionItem.Key = key;
missionItem.Value = myDictionary[key];
missionItems.Add(missionItem);
}
var json = JsonUtility.ToJson(missionItems);
Loading is straight forward, deserialize your data, then loop through all the items and add each one to the empty dicitionary.
var missionItems = JsonUtility.FromJson<List<MissionItem>>(json);
foreach (var item in missionItems)
{
myDictionary.Add(item.Key, item.Value);
}
Here is my final setup.
I call these on button press in another script (the UI pause menu save/load buttons)
private bool useEncryption = true;
private string encryptionCodeWord = "CodeWordHere";
private static string fileName = "name.json";
private static string defaultStatesPath => Path.Combine(Application.streamingAssetsPath, fileName);
private static string persistentStatesPath => Path.Combine(Application.persistentDataPath, fileName);
public void SaveStates(int slotIndex)
{
var filePath = persistentStatesPath;
if(!Directory.Exists(Application.persistentDataPath))
{
Directory.CreateDirectory(Application.persistentDataPath);
}
var json = JsonConvert.SerializeObject(_gameStateDictionary, Formatting.Indented);
if (useEncryption)
{
Debug.Log("Using Encryption");
json = EncryptDecrypt(json);
}
File.WriteAllText(filePath + slotIndex, json);
}
public void LoadStates(int SlotIndex)
{
var filePath = persistentStatesPath;
if(!File.Exists(filePath + SlotIndex))
{
filePath = defaultStatesPath;
}
var json = File.ReadAllText(filePath + SlotIndex);
if (useEncryption)
{
Debug.Log("Using Encryption");
json = EncryptDecrypt(json);
}
_gameStateDictionary = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
}
private string EncryptDecrypt(string data)
{
string modifiedData = "";
for (int i = 0; i < data.Length; i++)
{
modifiedData += (char)(data[i] ^ encryptionCodeWord[i % encryptionCodeWord.Length]);
}
return modifiedData;
}

Comparing N Objects In A Complex Structure C#

I have a set of instances of the Data class that I want to compare.
Each instance has an unknown number of items in it's Files property.
I want to compare each instance of Data to the others and set FoundDifference to true if a version difference is found between two files with the same Name value.
Is there a simple algorithm to accomplish this?
Here is a sample setup of how the objects might look.
In this example you'd want everything except for f1, f21, and f31 to set the FoundDifference to true
class Data
{
public string DC { get; set; }
public List<File> Files { get; set; }
}
class File
{
public string Name { get; set; }
public string Version { get; set; }
public bool FoundDifference { get; set; }
}
class Program
{
static void Main(string[] args)
{
Data d1 = new Data();
d1.DC = "DC1";
File f1 = new File();
f1.Name = "File1";
f1.Version = "1";
d1.Files.Add(f1);
File f2 = new File();
f2.Name = "File2";
f2.Version = "1";
d1.Files.Add(f2);
File f3 = new File();
f3.Name = "File3";
f3.Version = "1";
d1.Files.Add(f3);
//Another
Data d2 = new Data();
d2.DC = "DC2";
File f21 = new File();
f21.Name = "File1";
f21.Version = "1";
d2.Files.Add(f21);
File f22 = new File();
f22.Name = "File2";
f22.Version = "2";
d2.Files.Add(f22);
File f23 = new File();
f23.Name = "File3";
f23.Version = "1";
d2.Files.Add(f23);
//Another
Data d3 = new Data();
d3.DC = "DC3";
File f31 = new File();
f31.Name = "File1";
f31.Version = "1";
d3.Files.Add(f31);
File f32 = new File();
f32.Name = "File2";
f32.Version = "2";
d3.Files.Add(f32);
File f33 = new File();
f33.Name = "File3";
f33.Version = "5";
d3.Files.Add(f33);
//How Can I change All Files FoundDifference prop to true if FileName is the same and a difference is in Version is found??
Console.ReadLine();
}
I'd handle that by using a Dictionary<string, List<File>> to keep track of the files from each Data like this. First iterate all the files in all the datas then lookup the file name in the dictionary and if not found create a new list and add it. Then check if that list has any files with a different version. If one is found set all the flags and finally add the file to the list.
public void SetDifferences(IEnumerable<Data> datas)
{
var fileLookup = new Dictionary<string, List<File>>();
foreach(var file in datas.SelectMany(d => d.Files))
{
if(!fileLookup.TryGetValue(file.Name, out var fileList))
{
fileList = new List<File>();
fileLookup.Add(file.Name, fileList);
}
if(fileList.Any(f => f.Version != file.Version))
{
foreach(var other in fileList)
{
other.FoundDifference = true;
}
file.FoundDifference = true;
}
fileList.Add(file);
}
}

Dictionary stopping at loadingfromscreen

I run the code and it will not store the values it stops immediately at the loadingfromscreen. What its supposed to do is a multi-page application form that will reinput the values to the texbox's on the back button from the next form.
The ASP.net code is too long to post, but basically its just texbox's and dropboxes. If needed i can post it, but the main issue im 90% sure is the C# code.
UPDATE: When i say stop it continues the code but will not run the dictionary method...i have put a arrow where the method stops in DICTIONARY ONLY
C#:
public partial class employment_driversapplication_personalinfo : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Dictionary<string, string> DriversApplicationData = (Dictionary<string, string>) Session["DriversApp"];
try
{
if (Page.IsPostBack)
{
LoadMemoryFromScreen(DriversApplicationData);
}
else
{
LoadScreenFromMemory(DriversApplicationData);
}
}
catch //(Exception ex)
{
// throw new Exception("Exception occured in employment_driversapplication_personalinfo.aspx - Page_Load" + ex.Message);
}
finally
{
}
}
private void LoadMemoryFromScreen(Dictionary<string, string> DicDriversApp)
{
DicDriversApp["position"] = position.Text; <---Stops here (won't even store this)
DicDriversApp["fname"] = fname.Text;
DicDriversApp["middleinitial"] = middleinitial.Text;
DicDriversApp["lname"] = lname.Text;
DicDriversApp["birthday"] = birthday.Text;
DicDriversApp["proofofage"] = proofofage.SelectedValue;
DicDriversApp["address"] = address.Text;
DicDriversApp["city"] = city.Text;
DicDriversApp["state"] = state.Text;
DicDriversApp["email"] = email.Text;
DicDriversApp["phone"] = phone.Text;
DicDriversApp["altphone"] = altphone.Text;
DicDriversApp["citizen"] = citizen.SelectedValue;
DicDriversApp["whoreferred"] = whoreferred.Text;
DicDriversApp["famfriend"] = famfriend.Text;
DicDriversApp["relationship"] = relationship.Text;
DicDriversApp["rateofpayexpected"] = rateofpayexpected.Text;
DicDriversApp["rateofpaytype"] = RadioButtonList1.SelectedValue;
DicDriversApp["employedNow"] = employednow.SelectedValue;
DicDriversApp["curremployment"] = curremployment.Text;
DicDriversApp["pastAddress"] = pastaddress.SelectedValue;
DicDriversApp["previousAddress"] = previousaddress.Text;
DicDriversApp["previousCity"] = previouscity.Text;
DicDriversApp["previousZip"] = previouszip.Text;
DicDriversApp["previousState"] = previousstate.Text;
DicDriversApp["previousDuration"] = previousduration.Text;
DicDriversApp["previousAddress1"] = previousaddress1.Text;
DicDriversApp["previousCity1"] = previouscity1.Text;
DicDriversApp["previousZip1"] = previouszip1.Text;
DicDriversApp["previousState1"] = previousstate1.Text;
DicDriversApp["previousDuration1"] = previousduration1.Text;
Session["DriversApp"] = DicDriversApp;
}
private void LoadScreenFromMemory(Dictionary<string, string> DicDriversApp)
{
position.Text = DicDriversApp["position"];
fname.Text = DicDriversApp["fname"] ;
middleinitial.Text = DicDriversApp["middleinitial"];
lname.Text = DicDriversApp["lname"];
birthday.Text = DicDriversApp["birthday"];
proofofage.SelectedValue = DicDriversApp["proofofage"];
address.Text = DicDriversApp["address"];
city.Text = DicDriversApp["city"];
state.Text = DicDriversApp["state"];
email.Text = DicDriversApp["email"];
phone.Text = DicDriversApp["phone"];
altphone.Text = DicDriversApp["altphone"];
citizen.SelectedValue = DicDriversApp["citizen"];
whoreferred.Text = DicDriversApp["whoreferred"];
famfriend.Text = DicDriversApp["famfriend"];
relationship.Text = DicDriversApp["relationship"];
rateofpayexpected.Text = DicDriversApp["rateofpayexpected"];
RadioButtonList1.SelectedValue = DicDriversApp["rateofpaytype"];
employednow.SelectedValue = DicDriversApp["employedNow"];
curremployment.Text = DicDriversApp["curremployment"];
pastaddress.SelectedValue = DicDriversApp["pastAddress"];
previousaddress.Text = DicDriversApp["previousAddress"];
previouscity.Text = DicDriversApp["previousCity"];
previouszip.Text = DicDriversApp["previousZip"];
previousstate.Text = DicDriversApp["previousState"];
previousduration.Text = DicDriversApp["previousDuration"];
previousaddress1.Text = DicDriversApp["previousAddress1"];
previouscity1.Text = DicDriversApp["previousCity1"];
previouszip1.Text = DicDriversApp["previousZip1"];
previousstate1.Text = DicDriversApp["previousState1"];
previousduration1.Text = DicDriversApp["previousDuration1"];
}
try something like this:
private void LoadMemoryFromScreen()
{
Dictionary<string, string> driver = new Dictionary<string, string>();
driver.Add("position", position.Text);
driver.Add("othervalue",value.Text); ///etc..
Session["dict"] = driver;
}
then, later on if you want to access the values in your dictionary, use something like this:
var dict = (Dictionary<string, string>)Session["dict"];
problem with this is that you're going to have to use dict.GetElementAt(index) in order to retrieve values, and i don't think that's a very good approach.
This will work, but i kinda dont understand why you are using a dictionary to do this. I assume you are only loading data from 1 person on your page? Then you might as well just make a class with all the properties in it, and then you can just pass that around instead of using this dictionary/session hack.
public class DriversApplicationData
{
public string position {get;set;}
public string firstname {get;set;}
//etc
}
then, you can just do something like
DriversApplicationData data = new DriversApplicationData();
data.position = position.Text;
data.firstname = fname.Text;
this is gonna be alot easier to maintain and to retrieve/insert values.

when add emoticon to RichTextBox Error (**An item with the same key has already been added**)

I try to add emoticon in RichTextBox in WPF that use function below, when I type text :) from Textbox, it shows the good result but when I type the other text again it show error
(An item with the same key has already been added).this is code that i call from function Emoticons below :
private void btnSend_Click(object sender, RoutedEventArgs e)
{
Paragraph p = new Paragraph();
p.LineHeight = 1;
Run dd = new Run();
dd.Text= DateTime.Now.ToString("(HH:mm:ss)") + "Chat" + rtbMessage.Text;
rtbBody.Document.Blocks.Add(p);
Emoticons(dd.Text);
}
I type to fix it but still not solve. I hope all programmer will help me.
Thanks
///Function Emoticon////
private Dictionary<string, string> _mappings = new Dictionary<string, string>();
private string GetEmoticonText(string text)
{
string match = string.Empty;
int lowestPosition = text.Length;
foreach (KeyValuePair<string, string> pair in _mappings)
{
if (text.Contains(pair.Key))
{
int newPosition = text.IndexOf(pair.Key);
if (newPosition < lowestPosition)
{
match = pair.Key;
lowestPosition = newPosition;
}
}
}
return match;
}
// And also function which add smiles in richtextbox, here is it:
private void Emoticons(string msg)
{
//try
//{
_mappings.Add(#":)", "/Images/smiles/silly.png");
_mappings.Add(#">:o", "/Images/smiles/angry.png");
_mappings.Add(#":'(", "/Images/smiles/cry.png");
_mappings.Add(#"B-)", "/Images/smiles/cool.png");
_mappings.Add(#":^0", "/Images/smiles/laught.png");
_mappings.Add(#":-[", "/Images/smiles/blush.png");
_mappings.Add(#":-)", "/Images/smiles/happy.png");
_mappings.Add(#"?:|", "/Images/smiles/confuse.png");
_mappings.Add(#":x", "/Images/smiles/love.png");
var para = new Paragraph { LineHeight=1};
//Paragraph para = new Paragraph();
var r = new Run(msg);
para.Inlines.Add(r);
string emoticonText = GetEmoticonText(r.Text);
//if paragraph does not contains smile only add plain text to richtextbox rtb2
if (string.IsNullOrEmpty(emoticonText))
{
rtbBody.Document.Blocks.Add(para);
}
else
{
while (!string.IsNullOrEmpty(emoticonText))
{
TextPointer tp = r.ContentStart;
// keep moving the cursor until we find the emoticon text
while (!tp.GetTextInRun(LogicalDirection.Forward).StartsWith(emoticonText))
tp = tp.GetNextInsertionPosition(LogicalDirection.Forward);
// select all of the emoticon text
var tr = new TextRange(tp, tp.GetPositionAtOffset(emoticonText.Length)) { Text = string.Empty };
//relative path to image smile file
string path = _mappings[emoticonText];
var image = new Image
{
Source =
new BitmapImage(new Uri(Environment.CurrentDirectory + path,
UriKind.RelativeOrAbsolute)),
Width=Height=25,
};
//insert smile
new InlineUIContainer(image, tp);
if (para != null)
{
var endRun = para.Inlines.LastInline as Run;
if (endRun == null)
{
break;
}
else
{
emoticonText = GetEmoticonText(endRun.Text);
}
}
}
rtbBody.Document.Blocks.Add(para);
}
The reason you are getting this error is because you are adding an object in the dictionary with the same key, infact you are adding all the items in the _mappings dictionary on each call of your function Emoticons. You can't add duplicate entries in the dictionary. I have no idea why you are doing that, but you may fill up the dictionary once in your application startup or window load event and then use it later.
Move the following lines to any method/event where it would be executed only once.
_mappings.Add(#":)", "/Images/smiles/silly.png");
_mappings.Add(#">:o", "/Images/smiles/angry.png");
_mappings.Add(#":'(", "/Images/smiles/cry.png");
_mappings.Add(#"B-)", "/Images/smiles/cool.png");
_mappings.Add(#":^0", "/Images/smiles/laught.png");
_mappings.Add(#":-[", "/Images/smiles/blush.png");
_mappings.Add(#":-)", "/Images/smiles/happy.png");
_mappings.Add(#"?:|", "/Images/smiles/confuse.png");
_mappings.Add(#":x", "/Images/smiles/love.png");

ArrayList of Hashtables in C#

I want to have an ArrayList where it contains HashTables. I create a Hashtable and added values. I then added it to the ArrayList. I then changed the values of the Hashtables and added it again the Array List. It does not save the first values and ending having duplicated values which were exactly the same as the last values!
Any suggestions? Here is my code
namespace ValuesTest
{
internal class Class1
{
public static ArrayList StartList = new ArrayList();
public static Hashtable Start = new Hashtable();
static void Main(string[] args)
{
Start["active"] = true;
Start["name"] = "prog1";
Start["path"] = #"C:\programfiles\prog1";
Start["parameter"] = string.Empty;
StartList.Add(Start);
Start["active"] = false;
Start["name"] = "prog2";
Start["path"] = #"C:\programfiles\prog2";
Start["parameter"] = "/q";
StartList.Add(Start);
foreach (Hashtable HT in StartList)
{
Console.WriteLine(HT["active"] + " - " + HT["name"] + " - " + HT["path"] + " - " + HT["parameter"]);
// it will always gives
// False - prog2 - C:\programfiles\prog2 - /q
}
Console.ReadLine();
}
}
}
Move start to inside your Main function, and reinitialize it for the second add(and as #lasseespeholt said use List<T>).
static List<Hashtable> StartList = new List<Hashtable>();
static void Main(string[] args)
{
Hashtable Start = new Hashtable();
Start["active"] = true;
Start["name"] = "prog1";
Start["path"] = #"C:\programfiles\prog1";
Start["parameter"] = string.Empty;
StartList.Add(Start);
Start = new Hashtable();
Start["active"] = false;
Start["name"] = "prog2";
Start["path"] = #"C:\programfiles\prog2";
Start["parameter"] = "/q";
StartList.Add(Start);
You're modifying the one and only Start Hashtable object, you must create a new one:
Start = new Hashtable();
right after the first:
StartList.Add(Start);
Remember, you're only adding a reference to the object to the ArrayList: so what your code does is: populate a hashtable, add a reference to it to the list, modify it some more, and add the same reference again.
Would like to add, why are you using a hashtable? It would be far better to use a new class with the fields you desire - then they could have a PrintInfo, or a ToString override that gets the information you need - and presumably an Execute method.
Some more feedback on this: Although Nix already answered your question, I'd drop Hashtable as well (just as ArrayList it's dated), although your concept doesn't lend itself nice to it: You store string to object..
So, copying and changing we'd end up with
static void Main(string[] args)
{
Dictionary<string, object> Start = new Dictionary<string, object>();
Start["active"] = true;
Start["name"] = "prog1";
Start["path"] = #"C:\programfiles\prog1";
Start["parameter"] = string.Empty;
StartList.Add(Start);
Dictionary<string, object> Start = new Dictionary<string, object>();
Start["active"] = false;
Start["name"] = "prog2";
Start["path"] = #"C:\programfiles\prog2";
Start["parameter"] = "/q";
StartList.Add(Start);
But I'd go further: If you just want to spawn processes, that's what the class Process is for. It keeps just the same information (except for "active") in the StartInfo property.
Another, (better?) approach would be to create a value class for this set of information:
class YourStartInfo
{
public bool Active { get; set; }
public string Name { get; set; }
public string Path { get; set; }
public string Parameter { get; set; }
}
and changing your code to make use of that:
static List<YourStartInfo> StartList = new List<YourStartInfo>();
static void Main(string[] args)
{
StartList.Add(new YourStartInfo {
Active = true,
Name = "prog1",
Path = #"C:\programfiles\prog1";
Parameter = string.Empty
});
StartList.Add(new YourStartInfo {
Active = false,
Name = "prog2",
Path = #"C:\programfiles\prog2";
Parameter = "/q"
});
foreach (YourStartInfo startInfo in StartList)
{
// Access the information in a sane way, not as object here
if (startInfo.Active)
{
// Probably launch it?
}
}
Console.ReadLine();
}

Categories