.net中对文件操做,常常会用到这样几个类:数组
static void Main(string[] args) { string path =@"目录"; if (!Directory.Exists(path)) { Directory.CreateDirectory(path); //若是目录不存在就建立目录 } Console.ReadKey(); }
static void Main(string[] args) { string path=@"目录"; if (Directory.Exists(path)) { //Directory.Delete(path);//删除空目录 ,目录下没有文件了。 Directory.Delete(path, true);////无论空不空,都删! } Console.ReadKey(); }
File类能够进行对一些小文件的拷贝,剪切操做。还能读取一些文档文件ide
遍历目录下的文件:post
static void Main(string[] args) { IEnumerable<string> file1 = Directory.EnumerateFiles(@"目录"); IEnumerator<string> fileenum = file1.GetEnumerator(); while (fileenum.MoveNext()) //移动一下读取一个 { Console.WriteLine(fileenum.Current); } Console.ReadKey(); }
文件流类,负责文件的拷贝,读取编码
文件的读取:spa
using (Stream file = new FileStream("目录文件", FileMode.Open)) { byte[] bytes = new byte[4]; //读取数据的一个缓冲区 int len; while((len=file.Read(bytes,0,bytes.Length))>0) //每次读取bytes4字节的数据到 { //bytes中 string s = Encoding.Default.GetString(bytes,0,len); Console.WriteLine(s); } }
文件的写入:.net
//建立文件流 Stream file = new FileStream(@"d:\temp.txt", FileMode.Create); //按默认编码将内容读取到数组中 byte[] bytes = Encoding.Default.GetBytes("IO流操做读写换行\r\nhelloWord"); file.Write(bytes, 0, bytes.Length); //读取bytes数组,0位置开始读,读取长度 file.Close();//文件写入完毕后必定要关闭文件
static void Main(string[] args) { using (StreamWriter sw = new StreamWriter("e:\\temp.txt",false, Encoding.UTF8))//true表示日后追加 { sw.WriteLine("hello"); } Console.ReadKey(); }
static void Main(string[] args) { using(StreamReader sr = new StreamReader("e:\\temp.txt",Encoding.Default)) { string str; while ((str=sr.ReadLine()) != null) //每次读取一行 { Console.WriteLine(str); } } Console.ReadKey(); }