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類能夠進行對一些小文件的拷貝,剪切操做。還能讀取一些文檔文件ide

    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 //移動文件

遍歷目錄下的文件: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();
}
View Code

四.FileStream類:

    文件流類,負責文件的拷貝,讀取編碼

文件的讀取: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);
      }
}
View Code

文件的寫入:.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();//文件寫入完畢後必定要關閉文件
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();
}
相關文章
相關標籤/搜索