Search code examples
c#asp.netopenfiledialogasp.net-4.5

OpenFileDialog - how to set file path to input type=text element after a file is selected in c#


I want to add a "Browse" button to my asp.net 4.5.1 project without using FileUpload control.. The end users should be able to browse and select a file in their local folder, and I want to set the complete path of that folder to my <input type='text' id='rptScreenShot' ... /> element.

To do that, I've added a button and employed OpenFileFialog, which I couldn't use it straightforward as I need to use Threading based on my research, so my final code:

protected void btnUploadScreenshot_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog1 = new OpenFileDialog();
            openFileDialog1.Title = "Browse JPG Files";

            var thread = new Thread(new ParameterizedThreadStart(param => { if (openFileDialog1.ShowDialog() == DialogResult.OK) { rptScreenShot.Value = openFileDialog1.FileName; }; }));
            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();
        }

Once I click the "Browse" button, it pops up the File Dialog; however when I select a file and click "OK", the file path is not set to the related text input. Please note that when I do MessageBox.Show(openFileDialog1.FileName), it shows the complete path, but I couldn't manage it to set it to my input type=text element, so it's always blank.

How can I manage this? Any help would be appreciated.


Solution

  • AFAIK You can't create your own way to pop open the file browser from the server side code. This can only be done in the client code.

    What you can do is look around for some JS controls that can give you some functionality that you are looking for.