About
In this code snippet, we will see how to use the Open File Dialog in WFA C# apps.
In this example, I will use a WFA application. If you just want to know how to create/read/write files check out this example with a console application.
When we click the “Open File” button a file dialog will open. After selecting a file the path will get saved in a variable. Then we can either read or write to the selected file. We will be using the StreamWriter class to write to the file and the StreamReader class to read from the file. All these operations need to performed inside a try catch block to prevent the application from crashing if an exception occurs.
Let’s have a look below to see how to implement this.
First, let’s create the layout.
Code:
using System; using System.IO; using System.Windows.Forms; namespace WFAOpenFileDialog { public partial class Form1 : Form { public Form1() { InitializeComponent(); } string filePath = ""; private void fileReadButton_Click(object sender, EventArgs e) { //Exceptions need to be handled. As if the file cannot be accesed our application will crash. try { //Initialize StramReader by passing it the path of the file. StreamReader sr = new StreamReader(filePath); //Read from the file and save the string to a variable. string text = sr.ReadToEnd(); //Don't forget to close the StreamReader. sr.Close(); //Display the file contents in a label. readLabel.Text = text; } catch (FileNotFoundException) { MessageBox.Show("No file with such name was found!"); } catch (DirectoryNotFoundException) { MessageBox.Show("Directory doesnt exist!"); } catch (Exception ex) { MessageBox.Show("Something went wrong!" + ex.Data); } } private void writeButton_Click(object sender, EventArgs e) { //Get the text to be written to file from the text box. string text = writeTextBox.Text; //Exceptions need to be handled as if the file cannot be accesed our application will crash. try { //Initialize StramWriter by passing it the path of the file. StreamWriter sw = File.CreateText(filePath); //Write to the file. sw.Write(text); //You could use the WriteLine(); method if you want to write to the file line by line. //Don't forget to close the StreamReader. sw.Close(); } catch (Exception ex) { MessageBox.Show("Something went wrong!" + ex.Data); } } private void openFileButton_Click(object sender, EventArgs e) { //When the open file button is pressed the open file dialog will open. //After the user selects the file we we will get the file name from the open file dialog and save it to a variable. if (openFileDialog1.ShowDialog() == DialogResult.OK) { filePath = openFileDialog1.FileName; } //Display path in the label. filePathLabel.Text = filePath; } } }