Search code examples
c#winformsopenfiledialog

Prompt user with an output file dialog at program startup (initialize)


I am currently working with output files. I am in the process of building a program that request for the user to save an output file before the program does anything else. The purpose is that the program will write results to this output file. I have been able to get the output file dialog to appear with a button click. Is there away to prompt the user with output file dialog as soon as the program initializes?

Code-output file through button:

namespace open_document
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFile = new OpenFileDialog();
            openFile.Filter = "Text Files | *.txt";
            openFile.ShowDialog();          
            StreamReader infile = File.OpenText(openFile.FileName);

        }

    }
}

Solution

  • Why don't you use the Load event of the Form or Page, as per your requirement:

    Designer:

    this.Load += new System.EventHandler(this.MainForm_Load);
    

    Code:

    private void MainForm_Load(object sender, EventArgs e)
    {   
        OpenFileDialog openFile = new OpenFileDialog();
        openFile.Filter = "Text Files | *.txt";
        openFile.ShowDialog();          
        StreamReader infile = File.OpenText(openFile.FileName);
        // ... 
    }