Wednesday, October 9, 2013

Open File

Today a pretty easy topic, in which probably many will be interested though - I also admit googling it often, if I have forgotten the exact code again.
In this post I want to show, how to open a file using C# to either read from it or write in it.
Therefor, many methods exist, I here show the probably easiest and most comfortable one, which uses a StreamReader respectively StreamWriter.

Open File for Reading:
For that we need an instance of the class StreamReader. We initialize it with the path to the file we want to open. Subsequently the content can be read, e.g. line by line (for text formats) with ReadLine() or the complete context at once using ReadToEnd(). Important is also the closing and disposing of the used file afterwards. The following code reads the file filename from the path path line by line and prints each line on the screen:

System.IO.StreamReader sr = new System.IO.StreamReader("path\filename");
string line = "";
while ((line = sr.ReadLine()) != null) // read until no more lines are available
{
    MessageBox.Show(line);
}
sr.Close();
Alternatively, this code reads the whole content in one step:

System.IO.StreamReader sr = new System.IO.StreamReader("path\filename");
MessageBox.Show(sr.ReadToEnd());
sr.Close();

Open File for Writing:
This process can be implemented analogously, just with an instance of the class StreamWriter. We also hand the file path and name over in the constructor, as well as an optional Boolean parameter, which describes, whether we want to append to the file, if it already exists. Meaning: If the file already exists and we handover true, all data the program writes will be appended to the file. Otherwise, the file is replaced. The default value is false. If the file does not exist, the parameter has no impact, it is then created.
The following code opens the file filename in path and appends to it, if already existing, the line "test":

System.IO.StreamWriter sw = new System.IO.StreamWriter("path\filename");
sw.WriteLine("test");
sw.Close();

Finally I want to present the dialogs OpenFileDialog and SaveFileDialog. They are not related to the actual process of opening / saving files, but provide the dialogs known from Windows for opening / saving files, in which the user can select the desired file.
The following example shows a dialog for opening, if the user selects a file and confirms it, the program opens it with above method:

if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
    System.IO.StreamReader sr = new System.IO.StreamReader(openFileDialog1.FileName);
    MessageBox.Show(sr.ReadToEnd());
    sr.Close();
}

For writing you can do the same, or use the SaveFileDialog, which might be a bit more fitting.

No comments:

Post a Comment