码迷,mamicode.com
首页 > Windows程序 > 详细

C#中的文件操作1

时间:2015-05-16 17:59:55      阅读:283      评论:0      收藏:0      [点我收藏+]

标签:

1、 文件操作常用相关类

a)File              //操作文件,静态类,对文件整体操作。拷贝、删除、剪切等

b)Directory        //操作目录(文件夹),静态类

c)DirectoryInfo    //文件夹的一个“类”,用来描述一个文件夹对象

d)FileInfo         //文件类,用来描述一个文件对象

e)Path            //对文件或目录的路径进行操作(很方便)【字符串】

f)Stream         //文件流,抽象类

FileStream  //文件流,MemoryStream(内存流),NetworkStream(网络流)

StreamReader         //快速读取文本文件

StreamWriter          //快速写入文本文件

2、 Path类(对字符串操作)

  a) 目录和文件操作的命名空间System.IO

b) string ChangeExtension(string path, string extension) (*)

  修改文件的后缀,“修改”支持字符串层面的,没有真的给文件改名

  string s = Path.ChangeExtension(@"C:\temp\F3.png", "jpg")

 c) string Combine(string path1, string path2)

  将两个路径合成一个路径,比用+好,可以方便解决不加斜线的问题,自动处理路径分隔符的问题

  string s = Path.Combine(@"c:\temp","a.jpg")

 d) string GetDirectoryName(string path) (*)

  得到文件的路径名。Path.GetDirectoryName(@"c:\temp\a.jpg")

     string GetExtension(string path) 得到文件的扩展名

     string GetFileName(string path) 得到文件路径的文件名部分

string GetFileNameWithoutExtension(string path) 得到去除扩展名的文件名

string GetFullPath(string path) 得到文件的全路径。可以根据相对路径获得绝对路径。

string GetTempFileName()  得到一个唯一的临时文件名(*)

string GetTempPath() 得到临时文件夹的路径(*)

补充:Path.GetFileName()获取文件名

3、 操作目录

Directory和DirectoryInfo

a)void Delete(string path, bool recursive)     删除目录

b)recursive表示是否递归删除,如果recursive为false则只能删除空目录

c)bool Exists(string path)      判断目录是否存在

move()

CreateDirectory()

string[] GetDirectories(string path)  得到一个目录下的子目录

string[] GetDirectories(string path, string searchPattern, SearchOption searchOption)    通配符查找目录下的子目录,可以搜索到隐藏文件。

static string[] GetFiles(string path)  得到一个目录下的文件

string[] GetFiles(string path, string searchPattern, SearchOption searchOption)   通配符查找目录下的文件

DirectoryInfo GetParent(string path)  得到目录的父目录

4、 File类的方法

a)File.Copy(“source”, “targetFileName”, true);//文件拷贝,true表示当文件存在时“覆盖”,如果不加true,则文件存在报异常。

b)File.Exists();//判断文件是否存在

c)File.Move(“source”, “target”);//移动(剪切),思考如何为文件重命名?

  C#里面,重命名文件时,没有 rename 这个功能,使用的是FileInfo.MoveTo的方式,MoveTo 到原目录里一个新的名字,即实现了重命名

d)File.Delete(“path”);//删除。如果文件不存在?不存在,不报错

e)File.Create(“path”);//创建文件

 

操作文本文件

a)File.ReadAllLines(“path”, Encoding.Default);//读取所有行,返回string[]

b)File.ReadAllText(“path”, Encoding.Default);//读取所有文本返回string

c)File.ReadAllBytes(“path”);//读取文件,返回byte[]

===================================

a)File.WriteAllLines(“path”, new string[4] ,Encoding.Default);//将b)string数组按行写入文件。

c)File.WriteAllText(“path”, “string”);//将字符串全部写入文件

d)File.WriteAllBytes(“path”,new byte[5]);//将byte[]全部写入到文件

e)File.AppendAllText()//将string追加到文件

 

File.Open(); //返回FileStream

File.OpenRead();//返回只读的FileStream

File.OpenWrite();//返回只写的FileStream

 

C#中的文件操作1

标签:

原文地址:http://www.cnblogs.com/lcxBlog/p/4508160.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!