IO文件操作

一.IO文件的操作:

    .net中对文件操作,经常会用到这样几个类:

      • FileStream       (操作大文件)
      • Path               (操作路径)
      • File                 (操作小文件)
      • Directory         (目录操作)

二.Directory类:

    • 创建目录:
static void Main(string[] args)
{
    string path =@"目录";     
    if (!Directory.Exists(path))
    {
        Directory.CreateDirectory(path);    //如果目录不存在就创建目录
    }
    Console.ReadKey();
}
View Code
    • 删除目录:
static void Main(string[] args)
{
    string path=@"目录";
    if (Directory.Exists(path))
    {
        //Directory.Delete(path);//删除空目录  ,目录下没有文件了。
        Directory.Delete(path, true);////不管空不空,都删!
    }
    Console.ReadKey();
}
View Code

三.File类:

    File类可以进行对一些小文件的拷贝,剪切操作。还能读取一些文档文件

    1. void Delete(string path): //删除文件;
    2. bool Exists(string path): //判断文件是否存在;
    3. string[] ReadAllLines(string path): //将文本文件中的内容读取到string数组中;
    4. string ReadAllText(string path): //将文本文件读取为一个字符串
    5. void WriteAllLines(string path, string[] contents)://将string[]写入到文件中;
    6. void WriteAllText(string path, string contents)://将字符串contents写入到文件path
    7. AppendAllText: //向文件中附加内容;
    8. Copy //复制文件;
    9. Move //移动文件

遍历目录下的文件:

static void Main(string[] args)
{
    IEnumerable<string> file1 = Directory.EnumerateFiles(@"目录");
    IEnumerator<string> fileenum = file1.GetEnumerator();
    while (fileenum.MoveNext())   //移动一下读取一个
    {
        Console.WriteLine(fileenum.Current);
    }
    Console.ReadKey();
}
View Code

四.FileStream类:

    文件流类,负责文件的拷贝,读取

文件的读取:

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);
      }
}
View Code

文件的写入:

//创建文件流
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();//文件写入完毕后一定要关闭文件
View Code

五.文本文件的操作:

1.按行写入文本文件
static void Main(string[] args)
{
    using (StreamWriter sw = new StreamWriter("e:\\temp.txt",false, Encoding.UTF8))//true表示往后追加
    {
        sw.WriteLine("hello");
    }
    Console.ReadKey();
}
2.按行读取文本文件
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();
}
posted on 2017-03-05 11:17  风雪幻林  阅读(215)  评论(0编辑  收藏  举报