流有很多种,文件流是一种.
FileMode是枚举类型
.Append 追加
.Create 创建或覆盖
.CreateNew 创建 相同则抛出异常
.Open 打开
.OpenOrCreate 有则打开无则创建
.Truncate 打开并截取成0字节
StreamReader写入中文
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Write, FileShare.None);//创建文件流
StreamWriter sw = new StreamWriter(fs,Encoding.GetEncoding("gb2312"));//支持中文
sw.WriteLine("test");
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { FileStream fs = new FileStream(@"F:DotNetC#DotNet基础加强视频20110718 文件新建 文本文档.txt", FileMode.Open);//打开 int bufferSize = 1024;//定义缓冲区大小 byte[] buffer = new byte[bufferSize]; int n; while ((n = fs.Read(buffer, 0, bufferSize))> 0) { //字节数组转换成字符串 Console.WriteLine (Encoding.UTF8.GetString(buffer,0,n));//UTF8为文件编码类型 } //关闭文件流 fs.Close(); Console.Read(); } } }
读取整个文件
using (FileStream fs = File.OpenRead(@"F:DotNetC#DotNet基础加强视频20110718 文件新建 文本文档.txt")) { using (StreamReader sr = new StreamReader(fs, Encoding.UTF8)) { Console.WriteLine(sr.ReadToEnd()); } } Console.Read();
一行一行读取文件
using (FileStream fs = File.OpenRead(@"F:DotNetC#DotNet基础加强视频20110718 文件新建 文本文档.txt")) { using (StreamReader sr = new StreamReader(fs, Encoding.UTF8)) { string line; while ((line = sr.ReadLine()) != null) { Console.WriteLine(line); } } } Console.Read();
读取网页源代码
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using System.Net; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { using (Stream str = wc.OpenRead("http://www.baidu.com")) { using (StreamReader sr = new StreamReader(str, Encoding.UTF8)) { string line; while ((line = sr.ReadLine()) != null) { Console.WriteLine(line); } } } Console.Read(); } } }