美文网首页
C#大文件读取写入

C#大文件读取写入

作者: 之乎者也QAQ | 来源:发表于2020-02-20 15:38 被阅读0次

    接上一篇文章,继续大文件的问题

    1.这次我还是创建控制台程序,按自己需求自定义数组的大小读取

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.IO;
    namespace 文件的读写
    {
        class Program
        {
            static void Main(string[] args)
            {    
                using (Stream fs = new FileStream(@"C: \Users\xg\Desktop\计划表.txt", FileMode.Open))
                {
                    string path = @"C: \Users\xg\Desktop\bb.txt";
                    byte[] bytes = new byte[1024 * 1024];
                    int len;
                    while ((len = fs.Read(bytes, 0, bytes.Length)) > 0)
                    {
                        string s = Encoding.GetEncoding("utf-8").GetString(bytes, 0, len);
                        Console.Write(s);
                        MyStreamWriter(path, s);
                    }
                }
            //使用StreamWrite  StreamReader 不需要考虑文件的编码问题
            /// <summary>
            /// 写文件
            /// </summary>
            /// <param name="path">文件路径</param>
            /// <param name="Content">读取的字符串</param>
            static void MyStreamWriter(string path, string Content)
            {
                using (Stream inStream = new FileStream(path, FileMode.Create))
                using (StreamWriter write = new StreamWriter(inStream))
                {
                    write.WriteLine(Content);
                }
            }
         }
    }
    
    
    

    2.创建一个控制程序,逐行读取大文件,写入目标文件

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.IO;
    namespace 文件的读写
    {
        class Program
        {
            static void Main(string[] args)
            {
      string ss = @"C:\Users\xg\Desktop\计划表.txt";
                MyStreamReader2(ss);
     static void MyStreamReader2(string path)
            {
                string file = @"C: \Users\xg\Desktop\cb.txt";
                StringBuilder sb = new StringBuilder();
                using (Stream outStream = new FileStream(path, FileMode.Open))//打开文件流
                using (StreamReader reader = new StreamReader(outStream, Encoding.GetEncoding("utf-8")))//读文件流
                {
                    while (reader.Peek() > -1)//读下一个字符返货是否字符个数为0 
                    {
                        sb = sb.AppendLine(reader.ReadLine());//读取一行
                       using (Stream inStream = new FileStream(file, FileMode.Create))
                        using (StreamWriter write = new StreamWriter(inStream))
                        {
                            write.WriteLine(sb);
                        }
                    }
                }
    
             }
           }
       }
    
    

    相关文章

      网友评论

          本文标题:C#大文件读取写入

          本文链接:https://www.haomeiwen.com/subject/irbzfhtx.html