.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

 

posted @ 2016-04-11 00:12  ToBeStrong  阅读(745)  评论(0编辑  收藏  举报