I currently have a winform with a listbox control that allows a user to browse directories and add them to the listbox. These directory locations will then be saved using the application settings file (as a string?), but I'm not sure how I should separate each directory string. Upon reloading of the form, I would like all the directories to be loading into the listbox as individual items from the settings file.
So I technically have two questions:
What would be the most efficient way to save multiple locations within the application settings file?
How would I go about loading the directories into the listbox from the settings? (Remember, there's multiple directories)
My idea was to store all the directories in one string setting and separate them with a co开发者_Python百科mma, but I'm not sure if there's a more efficient method to do this.
NO!!!! NEVER DO THAT!!!! Comma can be included in folder name and if you use comma as separator it could bring many critical issues to your program.
you can use characters that are illegal in folder names in windows.
\ / : * ? " < > |
also you can not use \
and /
because path maybe stores as c:\\data\\
and using '\' as separator is bad, and also they maybe stored as c:/data/
so using /
is risky. I think using *
or |
maybe a good idea both because of they are illegal and they cannot be anywhere of a folder path and the string that has some folder paths concatenated is readable and can simply being recognized by see *
or |
as separator.
String[] paths = s.Split(new char[]{'*'}, StringSplitOptions.RemoveEmptyEntries);
listBox1.Items.AddRange(paths);
where s is string of concatenated folder paths you have read from setting file. also you can use
String[] paths = s.Split(new char[]{'*'}, StringSplitOptions.RemoveEmptyEntries);
listBox1.DataSource = paths;
You could do that, and then do a string.Split on the comma, and set the listbox's source to the result of the split.
string settings = GetFromConfig();
var items = settings.Split(',');
listBox1.DataSource = items;
You can use a StringCollection in the settings file.
Once in a collection you can just put them back into a List<String>
and then add the items back via ListBox.Items
property, specifically the Add
method.
精彩评论