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;
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
- [C#] FileStream Open File – how to open file using file stream
- [C#] FileStream Read File – how to safely read file stream
- [C#] Read Text File – how to read lines from text file
- [C#] Load Text File to String – how to load text from file to string
- [C#] Get Files from Directory – how to get files from directory
- [C#] Delete All Files – how to delete files from the specified directory
- [C#] Get Application Directory – how to get application or assembly folder
- [C#] File Attributes – how to get or set file attributes
- [C#] Get File Time – how to get last modification time of a file
- [C#] Open File With Associated Application – how to launch the default application
See also
- FileStream – MSDN – class to access file using stream interface
- FileMode – MSDN – enumeration how to open file (Open, Create, Append, …)
- FileAccess – MSDN – enumeration how to access file (Read, Write, ReadWrite)