Harikasai
Harikasai

Reputation: 1307

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

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?

Upvotes: 107

Views: 313972

Answers (4)

Prince Prajapati
Prince Prajapati

Reputation: 11

        int size = -1;
        OpenFileDialog openFileDialog1 = new OpenFileDialog();
        openFileDialog1.InitialDirectory = @"YOUR FILE PATH";  
        DialogResult result = openFileDialog1.ShowDialog(); 
        // Show the dialog.
        openFileDialog1.RestoreDirectory = true;
        openFileDialog1.Title = "BROWSE TEXT BLT";
        openFileDialog1.FilterIndex = 2;
        openFileDialog1.CheckFileExists = true;
        openFileDialog1.CheckPathExists = true;
        if (result == DialogResult.OK) // Test result.
        {
            string file = openFileDialog1.FileName;
            try
            {
                string text = System.IO.File.ReadAllText(file);
                size = text.Length;
            }
            catch (System.IO.IOException ex)
            {
                throw ex;
            }
            TXT_FOLDER_PATH.Text = file;
         }

Upvotes: 1

Divi
Divi

Reputation: 7691

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;
    OpenFileDialog openFileDialog1 = new OpenFileDialog();
    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.
}

Upvotes: 123

alireza0000
alireza0000

Reputation: 361

OpenFileDialog fdlg = new OpenFileDialog();
fdlg.Title = "C# Corner Open File Dialog" ;
fdlg.InitialDirectory = @"c:\" ;
fdlg.Filter = "All files (*.*)|*.*|All files (*.*)|*.*" ;
fdlg.FilterIndex = 2 ;
fdlg.RestoreDirectory = true ;
if(fdlg.ShowDialog() == DialogResult.OK)
{
textBox1.Text = fdlg.FileName ;
}

In this code you can put your address in a text box.

Upvotes: 35

Adam Rackis
Adam Rackis

Reputation: 83358

var FD = new System.Windows.Forms.OpenFileDialog();
if (FD.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
    string fileToOpen = FD.FileName;

    System.IO.FileInfo File = new System.IO.FileInfo(FD.FileName);

    //OR

    System.IO.StreamReader reader = new System.IO.StreamReader(fileToOpen);
    //etc
}

Upvotes: 53

Related Questions