简体   繁体   中英

Get File Path From File in Auto-Saved ListBox

I have a saved listBox. When someone exits the program, it will save all the names in the listBox and when they enter it will add all them back.

The thing is, when the form is opened and listBox2 is empty, it is fine and does its functions. But when the program loads items from the textbox into listBox2 automatically on Form_Load, I get the following error when I click on listBox2.

An unhandled exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll

Additional information: Index was out of range. Must be non-negative and less than the size of the collection.

on string fullFileName = selectedFiles[listBox2.SelectedIndex];

private void materialFlatButton3_Click_1(object sender, EventArgs e)
        {
            OpenFileDialog OpenFileDialog1 = new OpenFileDialog();
            OpenFileDialog1.Multiselect = true;
            OpenFileDialog1.Filter = "DLL Files|*.dll";
            OpenFileDialog1.Title = "Select a Dll File";
            if (OpenFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                // put the selected result in the global variable
                fullFileName = new List<String>(OpenFileDialog1.FileNames);


                foreach (string s in OpenFileDialog1.FileNames)
                {
                    listBox2.Items.Add(Path.GetFileName(s));
                    selectedFiles.Add(s);
                }

            }
        }

List<string> selectedFiles = new List<string>();
        private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
        {

            if (listBox2.SelectedIndex >= 0)
            {
                string fullFileName = selectedFiles[listBox2.SelectedIndex];
                textBox4.Text = fullFileName;
            }
            else
            {

            }




string path = @"C:\Save.txt";

       private void Form1_Load(object sender, EventArgs e)
                {
                    if (!File.Exists(path))
                    {

                        FileStream fs = File.Create(path);
                        fs.Close();

                    }
                    else
                    {
                        StreamReader sr = new StreamReader(path);
                        string line = string.Empty;
                        try
                        {
                            //Read the first line of text
                            line = sr.ReadLine();
                            //Continue to read until you reach end of file
                            while (line != null)
                            {
                                this.listBox2.Items.Add(line);
                                //Read the next line
                                line = sr.ReadLine();
                            }

                            //close the file
                            sr.Close();
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message.ToString());
                        }
                        finally
                        {
                            //close the file
                            sr.Close();
                        }




                            textBox3.Visible = false;
                            string text = File.ReadAllText(path, Encoding.UTF8);

                        }
                    }
                }

Your code has a big flaw, you have a ListBox with the file names, and a List<string> with the paths but you are saving only the data on the ListBox , so when you restore the content of the ListBox your List<string> remains empty, that's why it gives you an exception on the SelectedIndexChanged .

You need to store somehow the paths also and then restore it on load. The most simple solution can be to interleave the data on the file, save a file name from the listbox, a path from the list and so on until you saved everything, then when you read back it you restore a line for the listbox with the name and a line for the list with the path.

EDIT: Better, instead of saving the content from the ListBox save the content from the List<string> then you can do:

line = sr.ReadLine();
//Continue to read until you reach end of file
while (line != null)
{
    this.listBox2.Items.Add(Path.GetFileName(line));
    selectedFiles.Add(line);
    //Read the next line
    line = sr.ReadLine();
}

//close the file
sr.Close();

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