C# 文件操作

1.File类

Console.WriteLine(File.Exists("./1.txt"));

2.Directory类

 

foreach(string f in Directory.GetFiles("./")){
    Console.WriteLine(f);
}

3.DirectoryInfo类

DirectoryInfo f= new DirectoryInfo("./");
foreach(FileInfo item in f.GetFiles()){
    Console.WriteLine(item.Name);
}

  

 4

5.BinaryReader

using System;
using System.IO;
namespace APP{
    class MyClass{
        public static void Main(string[] args){
            FileStream fs = new FileStream("1.txt",FileMode.Open,FileAccess.Read,FileShare.Read);
            BinaryReader b= new BinaryReader(fs);
            for(int i=0;i<10;i++){
                Console.WriteLine(b.ReadChar());
            }
            b.Close();
            fs.Close();
        }
    }
}

 StreamWriter 类

using System;
using System.IO;
namespace App{
    class MyClass{
        public static void Main(string[] args){
            StreamWriter sw = new StreamWriter("10.txt",false);
            string str ="asklfaslkaskl";
            sw.Write(str);
            sw.Close();
            Console.WriteLine("写入完成!");
        }
    }
}
using System;
using System.IO;
namespace App{
    class MyClass{
        public static void Main(string[] args){
            FileStream fs = new FileStream("1.txt",FileMode.OpenOrCreate);
            StreamWriter sw = new StreamWriter(fs);
            string str ="asklfaslkaskl";
            sw.WriteLine(str);
            sw.Close();
            Console.WriteLine("写入完成!");
        }
    }
}

  StreamReader 类

操作: 读取hosts文件里面的内容

using System;
using System.IO;
namespace App{
    class MyClass {
        public static void Main(string[] args){
            string path =@"C:\Windows\System32\drivers\etc\hosts";
            StreamReader sr = new StreamReader(path,true);
            string str= sr.ReadLine();
            Console.WriteLine(str);
            while(str!=null){
                Console.WriteLine(str);
                str= sr.ReadLine();
            }
        }
    }
}

 

posted @ 2019-04-18 10:10  liliyou  阅读(98)  评论(0编辑  收藏  举报