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);
}
}
}
Code (C#)
public static void Main()
{
//Declare a OpenFileDialog object
OpenFileDialog objOpenFileDialog = new OpenFileDialog();
//Set the Open dialog properties
var _with1 = objOpenFileDialog;
_with1.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
_with1.FilterIndex = 1;
_with1.Title = "Demo Open File Dialog";
//Show the Open dialog and if the user clicks the Open button,
//load the file
if (objOpenFileDialog.ShowDialog == System.Windows.Forms.DialogResult.OK) {
string allText = null;
try {
//Read the contents of the file
allText = My.Computer.FileSystem.ReadAllText(objOpenFileDialog.FileName);
//Display the file contents in the TextBox
System.Console.WriteLine(allText);
} catch (Exception fileException) {
throw fileException;
}
}
//Clean up
objOpenFileDialog.Dispose();
objOpenFileDialog = null;
}