第一种:
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);