Reputation: 1196
I've seen a lot of times, programas that have something like textbox
that is used to get/save the path
of something... There's a button on it and when you click on it opens a prompt for you to select the directory, you know ?
How Could I do that?
I have to read a file.txt
, and I need my application to open this file.txt
, how I open this "prompt" ? Then I need to save a destination path
the same way... Is it actually a textbox
or something else?
Thanks
Upvotes: 0
Views: 3064
Reputation: 3255
You can use the OpenFileDialog
string path;
OpenFileDialog file = new OpenFileDialog();
if (file.ShowDialog() == DialogResult.OK)
{
path = file.FileName;
}
Now the file path is saved to the string, and you can then manipulate the file.
Upvotes: 1
Reputation: 6021
You need to add an OpenFileDialog
to your form (MSDN has more info)
This sample should explain it better than I could!
private void button1_Click(object sender, System.EventArgs e)
{
Stream myStream = null;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = "c:\\" ;
openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*" ;
openFileDialog1.FilterIndex = 2 ;
openFileDialog1.RestoreDirectory = true ;
if(openFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
if ((myStream = openFileDialog1.OpenFile()) != null)
{
using (myStream)
{
// Insert code to read the stream here.
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
}
Upvotes: 2
Reputation: 887295
You need to create a button next to the textbox.
In the button's Click event handler, create and show a SaveFileDialog
, then assign its result to the textbox's text.
Upvotes: 2