How to save last folder in openFileDialog?

前端 未结 8 1948
刺人心
刺人心 2021-02-14 00:51

How do I make my application store the last path opened in openFileDialog and after new opening restore it?

OpenFileDialog openFileDialog1 = new Ope         


        
8条回答
  •  北荒
    北荒 (楼主)
    2021-02-14 01:10

    I know this is a bit of an old thread, but I was not able to find a solution I liked to this same question so I developed my own. I did this in WPF but it should work almost the same in Winforms.

    Essentially, I use an app.config file to store my programs last path.

    When my program starts I read the config file and save to a global variable. Below is a class and function I call when my program starts.

    public static class Statics
    {
        public static string CurrentBrowsePath { get; set; }
    
        public static void initialization()
        {
            ConfigurationManager.RefreshSection("appSettings");
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
    
            CurrentBrowsePath = ConfigurationManager.AppSettings["lastfolder"];
        }
    }
    

    Next I have a button that opens the file browse dialog and sets the InitialDirectory property to what was stored in the config file. Hope this helps any one googling.

        private void browse_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog open_files_dialog = new OpenFileDialog();
            open_files_dialog.Multiselect = true;
            open_files_dialog.Filter = "Image files|*.jpg;*.jpeg;*.png";
            open_files_dialog.InitialDirectory = Statics.CurrentBrowsePath;
    
            try
            {
                bool? dialog_result = open_files_dialog.ShowDialog();
    
                if (dialog_result.HasValue && dialog_result.Value)
                {
                    string[] Selected_Files = open_files_dialog.FileNames;
    
                    if (Selected_Files.Length > 0)
                    {
                        ConfigWriter.Update("lastfolder", System.IO.Path.GetDirectoryName(Selected_Files[0]));
                    }
    
                    // Place code here to do what you want to do with the selected files.
                }
            }
            catch (Exception Ex)
            {
                MessageBox.Show("File Browse Error: " + Environment.NewLine + Convert.ToString(Ex));
            }
        }
    

提交回复
热议问题