文件操作
File中方法是静态方法 FileInfo中方法是实例方法
对文件的操作主要分为两部分1、对文件的操作2、对文件内容的操作
在使用文件路径对文件进行操作时,路径分为绝对路径和相对路径,使用相对路径比较好,因为不会受根目录的限制。但是在使用相对路径时要记住,当前目录是可执行文件(.exe文件)所在的目录。
string path="/Users/aaa/DeskTop/a.txt";//使用想对路径比较好,因为可以适应不同的电脑
if (File.Exists(path))//判断该路径上是否存在该文件返回bool类型的值
{
Console.WriteLine("file exist");
File.Delete(path);//删除文件
}
else{
File.Create(path);//参数是文件的路径 创建文件
}
创建 File.create(路径) (如果目标已经存在你要创建的文件,你新创建的文件会覆盖掉原来的文件)
删除 File.Delete(路径) 如果有文件流的话,先关闭文件流
复制 File.Copy(oldPath,newPath)新的路径中如果已经存在该文件,程序会中断;
移动File.Move(oldPath,newPath) 新的路径中如果已经存在该文件,程序会中断
move和copy的简单比较
copy功能可以有第三个参数File.Copy(topath,path,true); 指定是否覆盖原有文件,如果选择覆盖,即 使原路径已有该文件,也不会中断,move是没有第三个参数的
- 文件夹的操作
文件夹的操作有copy没操作,其他和文件的操作基本相同
创建文件夹 Directory.CreateDirectory(path);
移动文件夹Directory.Move(path, topath);//文件夹不能复制但是可以移动
删除文件夹 Directory.Delete(path,true);//有内容时不能直接删除,想要删除需要将第二个参数设置成true
- 目录查询
string currentPath = Directory.GetCurrentDirectory();查询当前文件目录
//第二个参数,查找指定关键字的文件
//第三个参数,指定查找模式,当前目录中查找或所有子目录中查找
string[] paths = Directory.GetFiles(path,"*",SearchOption.TopDirectoryOnly);
string[] paths2 = Directory.GetDirectories(path); 获取到带有路径的文件夹 查询文件就是GetFiles
foreach (var item in paths2)
{
string name = Path.GetDirectoryName(item); 只获取文件夹的名字
Console.WriteLine(name);
}
- 文件流
对文件内容操作的一种缓存。创建文件时,会自动生成一个文件流,删除一个文件时如果有文件流,要先
关闭文件流。(目前的一些操作不关闭文件流也看不出有什么影响,不过在以后大的数据流中可能会出现错误,所以从现在开始形成好的习惯)(详见http://write.blog.csdn.net/postlist)
文件流就是write时将字符串转换成byte数组,
读取时将不用byte数组转换成字符串
读和写会使文档流偏移 Seek 设置文档流的位置
记得要使用Flush() 和close()推送,关闭文档流
FileMthodd fi=new FileMethod(path); 在使用时需要创建实例对象,然后功能和 file基本相似,在create 的时候不需要参数,copy,move时只需要一个参数(目标路径)
public static void Main()
{
//文件流的位置,刚创建的文件流指向文件的开头
string path="/Users/neworigin/DeskTop/c.txt";
FileStream fs = null;
if (File.Exists(path))
{
Console.WriteLine("file exist");
fs = File.Open(path,FileMode.Open);
}
else{
fs = File.Create(path);
}
string str="the position have go after";
byte[] str_write = Encoding.Default.GetBytes(str);
fs.Write(str_write, 0, 24);
fs.Flush();
//在对文件流进行操作后,文件流的位置跟着向后偏移
//SeekOrigin枚举 第一个参数是文件流的偏移量
//Begin文件开头 Current当前文件流的位置 End文件的结尾
fs.Seek(0, SeekOrigin.Begin);//通过seek设置文件流的位置
byte[] str_read = new byte[100];
fs.Read(str_read, 0, 24);
string read = Encoding.Default.GetString(str_read);
Console.WriteLine(read);
fs.Close();
//尝试向文件流多次添加数据
}
public static void Main()
{
string path="/Users/neworigin/DeskTop/a.txt";
FileStream fs = null;//声明一个文件流
if (File.Exists(path))
{
Console.WriteLine("file exists");
fs = File.Open(path, FileMode.Open);
}
else
{
fs = File.Create(path);
}
// string str="hello word";//会覆盖文件中原有的内容
// //把字符串抓换成byte数组
// byte[] str_byte = Encoding.Default.GetBytes(str);
// //通过文件流的write方法,想文件中写入数据
// fs.Write(str_byte, 0, str_byte.Length);//0 也是数组中的位置(从数组中的哪一位开始写入文件)
// fs.Flush(); //清空缓存
// fs.Close();//关闭文件流
byte[] str_read = Encoding.Default.GetBytes("00000000000000000000000000000");
fs.Read(str_read, 5, 11);//0表示向数组中写入的位置 11表示写入的长度
string read = Encoding.Default.GetString(str_read);
Console.WriteLine(read);
}