文件目录、文件夹、记事本创建、值写入、读取记事本值
简单示范:
using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication1 { public class 文件操作 { public static void Main(string[] agrs) { 操作类 cz = new 操作类(); //注意:路径如果使用\要使用转义字符来表示,即是\\;或者把路径将\字符换成/;或者@""; //创建文件 cz.GetDirectoryInfo("D:\\代码创建","A"); //查看文件 cz.QueryDirect("D:\\代码创建"); //创建文件/删除文件 cz.Directory_D_C("D:\\代码创建", "B"); //创建Txt cz.GetFileInfo("D:\\代码创建\\A", "Text.txt"); //在Txt写入值 cz.GetStreamWriter("D:\\代码创建\\A\\Text.txt","你好程序员"); //读取文件学习 cz.GetFileStream("D:\\代码创建\\A\\Text.txt"); Console.ReadKey(); } } public class 操作类 { /// <summary> /// 【CreateSubdirectory】创建文件 /// </summary> /// <param name="path">路径</param> /// <returns></returns> public void GetDirectoryInfo(string path,string name) { DirectoryInfo info = new DirectoryInfo(path); info.Create(); //创建目录 if (!File.Exists(path+"\\"+name)) //文件是否存在 { info.CreateSubdirectory(name); //在指定路径上创建目录 Console.WriteLine("DirectoryInfo文件{0}创建完成", name); } } /// <summary> /// 【EnumerateDirectories】查看目录下文件 /// </summary> /// <param name="path"></param> public void QueryDirect(string path) { DirectoryInfo info = new DirectoryInfo(path); IEnumerable<DirectoryInfo> dir = info.EnumerateDirectories(); foreach (var vlue in dir) { Console.WriteLine("DirectoryInfo文件" + vlue.Name); } } /// <summary> /// 【Directory】类 是个静态类,不能创建实例,直接通过类名.类成员 /// </summary> /// <param name="path"></param> public void Directory_D_C(string path,string name) { if (!Directory.Exists(path + "\\" + name)) { Directory.CreateDirectory(path + "\\" + name); Console.WriteLine("Directory文件{0}创建完成", name); } else { Directory.Delete(path + "\\" + name); Console.WriteLine("Directory删除文件{0}完成", name); } } /// <summary> /// 【FileInfo】创建文件Txt /// </summary> /// <param name="path"></param> /// <param name="FileName"></param> public void GetFileInfo(string path,string FileName) { FileInfo fileinfo = new FileInfo(path + "\\" + FileName); if (!fileinfo.Exists) { fileinfo.Create(); //创建文件 Console.WriteLine("FileInfo文件{0}创建完成", FileName); } } /// <summary> /// 【StreamWriter】写值 /// </summary> /// <param name="path"></param> /// <param name="str"></param> public void GetStreamWriter(string path, string str) { StreamWriter sw = new StreamWriter(path); sw.WriteLine(str); //向文件写值 sw.Flush(); //刷新缓存 sw.Close(); //关闭流 Console.WriteLine("StreamWriter写值{0}完成", str); } /// <summary> /// 【FileStream】读取文件值 /// </summary> /// <param name="path"></param> public void GetFileStream(string path) { if (File.Exists(path)) { FileStream fst = new FileStream(path, FileMode.Open, FileAccess.Read); byte[] byts = new byte[fst.Length]; //定义字节数组 fst.Read(byts,0,byts.Length); //读取文件学习 char[] c = Encoding.UTF8.GetChars(byts);//将自己转换到字符数组中 foreach (var v in c) { Console.WriteLine("FileStream读取值:" + v); //输出 } fst.Close(); //关闭流 } } } }