常用脚本(十二)C#_文件操作

第一种:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace Memory_2
{
    class Program
    {
        static void Main(string[] agrs)
        {
            //文件操作
            string path = @"D:\Test";
            //是否存在文件夹
            if (!Directory.Exists(path))
            {
                //不存在创建文件夹
                Directory.CreateDirectory(path);
            }

            //文件路径拼接
            //path += @"\1.txt";
            path = Path.Combine(path, "1.txt");
            //第一种文件读写
            //如果文件不存在,创建文件
            if (!File.Exists(path))
            {
                File.Create(path);
            }
            //写内容
            File.WriteAllText(path, "飞羽今天也感冒了");
            //读内容
            Console.WriteLine(File.ReadAllText(path));

            Console.ReadKey();
        }
    }
}

第二种:

//第二种
            //第二个参数
            //Create:如果文件不存在创建,如果文件存在覆盖
            //Append:文件后方追加字符
            //Open:打开文件,如果文件不存在,崩溃
            //OpenOrCreate:打开文件,如果不存在,则创建
            //第三个参数
            //三种权限
            //write 只写
            //read 只读
            //readwrite 读写
            FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write);//参数一:路径、参数二:文件模式、参数三:读写权限
            //把字符串转成二进制
            byte[] bs = new UTF8Encoding().GetBytes("明天圣诞节,叮叮当,叮叮当,铃儿响叮当。。。");
            //参数一:数组、参数二:从哪开始写入、参数三:长度
            fs.Write(bs, 0, bs.Length);
            fs.Close();//关闭文件流

            //读
            fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Read);
            //创建空二进制数组
            byte[] bs2 = new byte[fs.Length];
            //读
            fs.Read(bs2, 0, bs2.Length);
            //转成字符串
            string s = new UTF8Encoding().GetString(bs2);
            fs.Close();
            Console.WriteLine(s);

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值