简体   繁体   中英

C# - Storing multiple directories in settings and loading them into listbox

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:

  1. What would be the most efficient way to save multiple locations within the application settings file?

  2. 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 comma, 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.

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