C#_读写Txt文档

通过流的方式读取文件内容,和为txt文本进行写入

需要引用System.IO


    //读取:
    public static void Read(string filePath)
    {
        //创建读取流,并指定路径文件
        StreamReader sr = new StreamReader(filePath);
        //读取文件的所有字符
        string str = sr.ReadToEnd();
        Console.WriteLine(str.ToString());
        //关闭流
        sr.Close();
    }
    //写入:
    public static void Wirte(string filePath)
    {
        //检查是否存在该文件,若存在则删除
        if (File.Exists(filePath)) File.Delete(filePath);
        //根据路径创建流文件
        FileStream fs = new FileStream(filePath, System.IO.FileMode.Create);
        //创建一个写入流,写入文件为fs
        StreamWriter sw = new StreamWriter(fs);
        string str = "要写入的string字符串";
        sw.Write(str);
        //清空缓冲区
        sw.Flush();
        //关闭流
        sw.Close();
        //关闭文件
        fs.Close();
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值