目录
1.file类:静态类
绝对路径:string path = “/Users/neworigion/Desktop/a.txt”;
相对路径: b.txt”; 当前目录是当前程序生成的可执行文件的目录
1.1 创建文件
File.Create(path);
1.2 删除文件
File.Delete(path);
1.3 文件流
对文件内容的一种数据缓存,
创建文件时,会自动生成一个文件流,删除前,要先删除文件流
FileStream fs = File.Create(path); fs.close();
1.4 判断文件是否存在
File.Exists(path);
1.5 拷贝文件,覆盖
File.Copy(path,path2,true);
1.6 移动文件
只有2个参数,重复则抛出异常,相当于删除,
移动前注意文件流的关闭
File.Move(path,path2);
1.7 打开文件
FileStream fs = null;
fs = File.Open (path2, FileMode.Open);
1.8 写入数据
string s = " hello"; //a.txt aaaaabbbbbccccc
byte[] b = Encoding.Default.GetBytes (s); //将字符串转换为byte数组
fs.Write (b, 0, b.Length); //a.txt hellobbbbbccccc
1.9 读出数据
// byte[] st = new byte[100];
byte[] st = Encoding .Default .GetBytes("00000000000");
fs.Read (st, 0, 5); //读取数据,并保存到数组中
//第二个参数:向数组中写入的位置
string ss = Encoding.Default.GetString (st); //byte数组转换为string //结果为:bbbbb
1.10 清除缓存
fs.Flush ();
1.11 关闭文件流
fs.Close();
//刚创建的文件流位置指向文件的开头
//对文件流操作后,文件流的位置跟着向后移
1.12 设置文件流的位置
fs.Seek(0,SeekOrigin.Begin);
Seekorigin 是枚举类型
Begin 文件开头
Current 当前文件流的位置
End 文件的结尾
//StreamWriter 和 StreamReader
StreamWriter sw = new StreamWriter (fs); //通过fs创建一个专门进行写操作的流
sw.Write ("aaaaa"); //原来的内容将会被替代 a.txt bbbbbbbbbb
sw.Flush (); //aaaaabbbbb
sw.Write ("0000a"); //aaaaa0000a
sw.Flush ();
fs.Seek (0, SeekOrigin.Begin);
StreamReader sr = new StreamReader (fs);
string str = sr.ReadToEnd(); //直接读到尾
Console.WriteLine (str);
sw.Close ();
sr.Close ();
fs.Close (); //只有fs.Close ();也可
2 fileInfo类
fileinfo中的方法都是实例方法,要通过对象调用方法
2.1 创建文件
FileInfo fi = new FileInfo (path);
FileStream fs = fi.Create (); fs.close()
2.2 移动文件
fi.MoveTo(path2);
2.3 拷贝文件
fi.CopyTo(path2);
2.4 删除文件
fi.Delete(path);
2.5 判断文件是否存在
fi.Exists(path);
3 Directory类
路径
string path2 = “/Users/neworigin/Desktop/bb”;
string path3 = “/Users/neworigin/Desktop/cc/”;
3.1 创建文件
Directory.CreateDirectory (path);
3.2 删除文件
非空则设置为true
Directory.Delete (path,true);
3.3 移动文件
Directory.Move (path, path2);
3.4 获取某个目录下关键字文件名字的数组
string[] paths = Directory.GetFiles (path2,”*”, SearchOption.TopDirectoryOnly);
foreach (string item in paths) //默认当前目录下查找
{Console.WriteLine (item);} // SearchOption.AllDirectories
foreach (string item in paths)
{
//Console.WriteLine (item);
string name = Path.GetFileName (item); //去除路径,只剩名字
Console.WriteLine (name);
File.Copy (item, path3 + name); //拷贝到新目录下
}
3.5 获取应用程序当前的工作目录
string t = Directory.GetCurrentDirectory();
3.6 获取指定目录的父目录
DirectoryInfo f = Directory.GetParent(t);