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 andFileAccess enumerations as parameters.

FileStream typical use

This is typical code when opening file using FileStream. It's important to always close the stream. If you don't close the stream it can take a minute to be file again accessible (it will wait to garbage collector to free the FileStream instance and close the file).

[C#]
using System.IO;

FileStream fileStream = new FileStream(@"c:\file.txt", FileMode.Open);
try
{
  // read from file or write to file
}
finally
{
  fileStream.Close();
}

Open file examples

Following examples show the most common cases how to open a file for reading or writing or how to create a file.

[C#] Open existing file for read and write.
FileStream fileStream = new FileStream(@"c:\file.txt", FileMode.Open);


[C#] Open existing file for reading.
FileStream fileStream = new FileStream(@"c:\file.txt", FileMode.Open, FileAccess.Read);


[C#] Open existing file for writing.
FileStream fileStream = new FileStream(@"c:\file.txt", FileMode.Open, FileAccess.Write);


[C#] Open file for writing (with seek to end), if the file doesn't exist create it.
FileStream fileStream = new FileStream(@"c:\file.txt", FileMode.Append);


[C#] Create new file and open it for read and write, if the file exists overwrite it.
FileStream fileStream = new FileStream(@"c:\file.txt", FileMode.Create);


[C#] Create new file and open it for read and write, if the file exists throw exception.
FileStream fileStream = new FileStream(@"c:\file.txt", FileMode.CreateNew);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值