c#文件流

流有很多种,文件流是一种.

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:\DotNet\C#\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:\DotNet\C#\DotNet基础加强视频\20110718 文件\新建 文本文档.txt")) { using (StreamReader sr = new StreamReader(fs, Encoding.UTF8)) { Console.WriteLine(sr.ReadToEnd()); } } Console.Read();
一行一行读取文件
using (FileStream fs = File.OpenRead(@"F:\DotNet\C#\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(); } } }

 

转载于:https://www.cnblogs.com/danznb/p/3477257.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值