C#文件操作方法整理

1 文件创建

1.1通过Create()方法创建非UTF-8编码文件

创建文件:File类 FileInfo类
文件格式:UTF-8编码文件与非UTF-8编码文件

public static FileStream Create(string path,int bufferSize,FileOptions options)

path:要创建的文件路径及名称

bufferSize:用于读取和写入文件的已放入缓冲区的字节数

options:FileOptions值之一,描述如何创建或覆盖该文件。

返回值:FileStream对象。

例1:纯文本格式文本文件创建 同名则覆盖
         FileStream fs = File.Create("D:\\test.txt");

例2:创建指定缓冲区大小的文件
          string path = "D:\\test.txt";
          using (FileStream fs = File.Create(path, 1024))
          {
              Byte[] info = new UTF8Encoding(true).GetBytes("This is some text in the file.");
              fs.Write(info, 0, info.Length); 
           }

例3:创建可一步读取和写入的文本文件

File.Create( "D:\\test.txt",1024,FileOptions.Asynchronous);

1.2通过CreateText()方法创建UTF-8编码文件

public static StreamWriter Create(string path);

path:要创建的文件路径及名称

返回值:Stream Writer对象,它使用UTF-8编码写入制定的文件。

例1:创建XML文件,并向其中写入文本。

          string path = @"D:\MyTest.xml";
          using(StreamWriter sw=File.CreateText(path))
          {
              sw.WriteLine("<TextBlock>");
              sw.WriteLine("<TextBlock>");
              sw.WriteLine("<TextBlock>"); 
              sw.WriteLine("</TextBlock>");
          }

例2:创建一个位图文件

          string path = @"D:MyTe
          File.CreateText(path);

1.3 FileInfo创建文件

          FileInfo fileInfo = new FileInfo("FileInfoMethord.txt");//示例化FileInfo类
          StreamWriter sw = fileInfo.CreateText();//创建文件
          sw.Write("This is FileInfo Methord.");//向文件中写入信息

          sw.Close();//释放资源

2 文件打开   

2.1 以读/写方式打开文件

public static FileStream Open(string path,FileMode mode)
path:要打开的文件路径
mode:文件打开方式(点击查看FileMode类型)
返回值:FileStream类,以指定模式打开的指定路径上的的FileStream,具有读写访问权限并且不共享。
例1:打开一个可读/写文件
         string path = "D:\\test.txt";
         File.Open(path, FileMode.Open);
例2:打开一个不存在的文件,以读写的方式创建并打开
         string path = "D:\\test1.txt";
         File.Open(path, FileMode.OpenOrCreate);
例3:打开文件时清空文件内容,然后进行读写操作
         string path = "D:\\test.txt";
         File.Open(path, FileMode.Truncate);
例4:打开文件将光标移动到文件尾,然后在文件尾进行读写操作
         string path = "D:\\test.txt";
         File.Open(path, FileMode.Append);
例5:使用FileInfo类实现对文件以读写方式打开
         FileInfo  fileinfo=new FileInfo("text.txt");
         using(Stream stream=fileinfo.Open(”FileMode.Open))
        {
Byte [] info=new UTF8Encoding(true).GetBites("民以食为天");
                stream.Write(info,0,info.Length);
         }

2.2 以只读方式打开文件

例1:使用File类的OpenRead方法实现
        public static FileStream OpenRead(string path)
        path:文件路径
        返回值:FileStream类型

2.3以写入方式打开文件

例1:使用File类的OpenRead方法实现

        public static FileStream OpenWrite(string path)
        path:文件路径
        返回值:FileStream类型       


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值