Search code examples
c#foreachrefactoringfolderbrowserdialog

c# how to avoid repetition in foreach block


In my program, what user types on Data Grid View are set to file names and saved. I use Folder Browser Dialog for the saving function. The problem is the whole process is repeated through foreach loop and the folder browser dialog pops up for every single file. I just want it to be shown just once and all files are to be saved in a same folder.

my code

            
            foreach(File file in fileList)
            {
                if (file.fileSelection == true)
                {
                    fileList.Add(file);

                    //some code here

                    dataGridView1.Refresh();

                    FolderBrowserDialog fbd1 = new FolderBrowserDialog();
                    fbd1.ShowNewFolderButton = true;
            
                    if (fbd1.ShowDialog() == DialogResult.OK)
                    {
                        if (string.IsNullOrEmpty(file.newFilename) == false) 
                        {
                            file.newPath = Path.GetFullPath(fbd1.SelectedPath + "\\" + file.newFilename);
                            file.newFileDirectory = fbd1.SelectedPath;
                        }
                    }

                    Microsoft.Office.Interop.Word.Document wordDoc = new Microsoft.Office.Interop.Word.Document();
                    Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();
                    object wordFileFormat = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatPDF;
                    object o = Missing.Value;
                    object oTrue = true;
                    object oFalse = false;
                    wordDoc.SaveAs2(file.newFileDirectory + "\\" + file.newFilename + ".pdf", ref wordFileFormat, o, o, o, o, o, o, o, o, o, o, o, o, o, o, o);
                    wordDoc.Close(oFalse, o, o);
                    wordApp.Quit(o, o, o);
                }
            }            
           

Solution

  • As far as I can see you only need to move the dialog out of the loop, you just need to save the dialog result in a variable so it can be checked inside the loop:

    FolderBrowserDialog fbd1 = new FolderBrowserDialog();
    fbd1.ShowNewFolderButton = true;
    var dialogResult = fbd1.ShowDialog();
    
    foreach(File file in fileList)
    {
       ...
       if(dialogResult == dialogResult.OK){
           if (string.IsNullOrEmpty(file.newFilename) == false) 
           {
                file.newPath = Path.GetFullPath(fbd1.SelectedPath + "\\" + file.newFilename);
                file.newFileDirectory = fbd1.SelectedPath;
            }
       }
       ...
    }
    

    You might also consider placing the entire loop inside the dialogResult-check.