FileStream Open File [C#]

This example shows how to open files for reading or writing, how to load and save files using FileStream in C#. To open file create instance of FileStream class with FileMode and FileAccess enumerations as parameters.

Use FileStream with „using“ statement

It's the best practice to use FileStream with using statement. The using statement ensures that Dispose method is called (even if an exception occurs). The Dispose method releases both managed and unmanaged resources and allows others to access the file. If you don't dispose the stream it can take a minute to file to be accessible again (it waits to garbage collector to free the FileStream instance and close the file).

Open existing file for read and write

The following examples require to add namespace using System.IO;

[C#]
using (var fileStream = new FileStream(@"c:\file.txt", FileMode.Open))
{
    // read from file or write to file
}

Open existing file for reading

[C#]
using (var fileStream = new FileStream(@"c:\file.txt", FileMode.Open, FileAccess.Read))
{
    // read from file
}

Open existing file for writing

[C#]
using (var fileStream = new FileStream(@"c:\file.txt", FileMode.Open, FileAccess.Write))
{
    // write to file
}

Open file for writing (with seek to end), if the file doesn't exist create it

[C#]
using (var fileStream = new FileStream(@"c:\file.txt", FileMode.Append))
{
    // append to file
}

Create new file and open it for read and write, if the file exists overwrite it

[C#]
using (var fileStream = new FileStream(@"c:\file.txt", FileMode.Create))
{
    // write to just created file
}

Create new file and open it for read and write, if the file exists throw exception

[C#]
using (var fileStream = new FileStream(@"c:\file.txt", FileMode.CreateNew))
{
    // write to just created file
}

Files and Folders Examples


See also

015)

;