.Net读写文件方法

1.文件的读取常用的有 FileStream、StreamReder、 File.ReadAllText()、 File.ReadAllLines()等。

   对应的写入方式有 FileStream、StreamWriter、File.WriteAllLines()、File.WriteAllText()等。

2.获取文件的路径

  (1)当前应用程序执行的路径:

      1. Environment.CurrentDirectory()   //获取和设置当前目录的完全限定路径。

      2.Directory.GetCurrentDirectory()    //获取应用程序的当前工作目录。

      3.AppDomain.CurrentDomain.BaseDirectory  //当前应用程序域基目录

    3.Assembly.GetExecutingAssembly().Location  //获取应用程序的完整路径(如:.exe的完整路径(包含.exe))

  (2)Web服务器虚拟目录转化物理路径:HttpContext.Current.Server.MapPath(fileName); 

3. 文件的读取和写入,以控制台为例。

    var physicsPath = Environment.CurrentDirectory??Directory.GetCurrentDirectory();
            var fileFolder = Directory.GetParent(Directory.GetParent(physicsPath).FullName).FullName;
            var filePath = Path.Combine(fileFolder, "file/lesson1.txt");
            var writePath = Path.Combine(fileFolder, "file/readAllLines_1.txt");

  (1) File.ReadAllLines、File.WriteAllLines

1 //1.File.ReadAllLines、File.WriteAllLines
2  var lines = File.ReadAllLines(filePath);
3  File.WriteAllLines(writePath,lines,Encoding.UTF8);
View Code

 

  (2)FileStream,通过FileMode来控制读亦或写,FileSteam读写比较精细,可控制bytes的大小,并循环读写来实现大文件的Copy

//2.FileStream
                var streamWriterPath = Path.Combine(fileFolder, "file/fileStream_1.txt");
            using (var fread=new FileStream(filePath,FileMode.Open))
            {
                var bytes = new byte[fread.Length];
                int len= fread.Read(bytes, 0, bytes.Length);

                using (var fwiter=new FileStream(streamWriterPath,FileMode.Append))
                {
                    fwiter.Write(bytes,0,len);
                }
            }
View Code

 

 (3)StreamReder、StreamWriter

 //3.StreamReader、StreamWrite
            var streamPath = Path.Combine(fileFolder, "file/Stream_1.txt");
            var line = string.Empty;
            using (var sReader=new StreamReader(filePath,Encoding.UTF8))
            {
                using (var sWriter = new StreamWriter(streamPath, false, Encoding.UTF8))
                {
                    while ((line = sReader.ReadLine())!= null)
                    {
                       sWriter.WriteLine(line);
                    }
                }
            }
View Code

 

转载于:https://www.cnblogs.com/wlxFighting/articles/5376643.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值