How to add browse file button to Windows Form using C#

Harikasai picture Harikasai · Feb 15, 2011 · Viewed 266.7k times · Source

I want to select a file on the local hard disk when I click a "Browse" button.

I don't have any idea how to use the OpenFileDialog control. Can anyone help me?

Answer

Divi picture Divi · Feb 15, 2011

These links explain it with examples

http://dotnetperls.com/openfiledialog

http://www.geekpedia.com/tutorial67_Using-OpenFileDialog-to-open-files.html

private void button1_Click(object sender, EventArgs e)
{
    int size = -1;
    DialogResult result = openFileDialog1.ShowDialog(); // Show the dialog.
    if (result == DialogResult.OK) // Test result.
    {
       string file = openFileDialog1.FileName;
       try
       {
          string text = File.ReadAllText(file);
          size = text.Length;
       }
       catch (IOException)
       {
       }
    }
    Console.WriteLine(size); // <-- Shows file size in debugging mode.
    Console.WriteLine(result); // <-- For debugging use.
}