1. File和Directory类
这两个类属于静态类,经常用到的比如File.Exists(string path), Directory.Exists(string path), Directory.GetCurrentDirectory(), Directory.SetCurrentDirectory(string path);
另外还有FileInfo和DirectoryInfo类,属于实例类,用法跟File和Directory差不多,就是要先实例化出来
当单一调用的时候优先用File和Directory类,如果操作很多,则用FileInfo和DirectoryInfo类会更好
2. FileStream类
用于指向文件的流操作,读写文档没StreamReader和StreamWriter方便
当然FileStream类最牛逼的地方在于Seek(long offset, SeekOrigin)这个方法
FileStream(string fileName, FileMode);
FileStream(string fileName, FileMode, FileAccess);
public enum FileMode { Append, Create, CreateNew, Open, OpenOrCreate, Truncate }
public enum FileMode
public enum FileAccess { Read, ReadWrite, Write }
public enum FileAccess
3. FileWriter
虽然FileWriter能够直接对文件写入,但是没有更多选项,所以一般要先创建一个FileStream,再创建FileWriter
4.FileReader
与FileWriter一样,但是FileStream的FileMode要改改
Read的时候可能会有文件不存在的BUG,所以要么加上try..catch,要么先判断exists
5. Path类
静态类,主要有GetDirectoryName和GetFileName两个方法
下面这段代码集成了上面的内容
using System; using System.Collections.Generic; using System.Linq; using System.Text; using MySql.Data; using MySql.Data.Entity; using MySql.Data.MySqlClient; using System.IO; namespace test4 { class Program { const string FILE = @"C:\Users\Administrator\Desktop\test.txt"; const string DIRECTORY = @"C:\Users\Administrator\Desktop\"; static void Main(string[] args) { if (File.Exists(FILE)) { Console.WriteLine("test.txt exist on desktop"); } if (Directory.Exists(DIRECTORY)) { Console.WriteLine("Desktop directory exists"); } Console.WriteLine(Directory.GetCurrentDirectory()); Console.WriteLine(Path.GetDirectoryName(FILE)); Console.WriteLine(Path.GetFileName(FILE)); //FileStream fst = File.OpenRead(FILE); //StreamWriter sw = new StreamWriter(FILE, true); FileStream fst = new FileStream(FILE, FileMode.Append | FileMode.OpenOrCreate); StreamWriter sw = new StreamWriter(fst); sw.WriteLine("xueyiyi"); sw.Close(); fst.Close(); //try //{ // fst = new FileStream(FILE, FileMode.Open); // StreamReader sr = new StreamReader(fst); // string str; // while ((str = sr.ReadLine()) != null) // { // Console.WriteLine(str); // } // sr.Close(); // fst.Close(); //} //catch (IOException e) //{ // Console.WriteLine("An IO exception has been thrown!"); // Console.WriteLine(e.ToString()); // return; //} if (File.Exists(FILE)) { fst = new FileStream(FILE, FileMode.Open); StreamReader sr = new StreamReader(fst); string str; while ((str = sr.ReadLine()) != null) { Console.WriteLine(str); } sr.Close(); fst.Close(); } else { Console.WriteLine(FILE + " does not exist"); } } } }
用StreamWriter类可以简单实现文件写入
StreamWriter s =
new
StreamWriter(address +
"/Menu.ini"
,
true
);
s.WriteLine(openFileDialog1.FileName);
s.Flush();
s.Close();
StreamReader sr =
new
StreamReader(address +
"/Menu.ini"
);
while
(sr.Peek()>=0)
{
string
str = sr.ReadLine();
}
sr.Close();