C# - 分割大文本文件

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yuxuac/article/details/90053353

将一个大的文本文件分割成若干个小文本文件。

​
        public static void Split()
        {
            int lineOfEach = 10000;
            int fileIndex = 1;

            string file = @"D:\Work\YourBigFile.csv";
            var outputFile = Path.GetFileNameWithoutExtension(file) + "_" + fileIndex + ".csv";
            string headerLine = "";
            int lineIndex = 1;

            StreamWriter sw = new StreamWriter(outputFile, false, Encoding.UTF8);
            using (StreamReader sr = new StreamReader(file, Encoding.UTF8))
            {
                headerLine = sr.ReadLine();
                while (!sr.EndOfStream)
                {
                    var line = sr.ReadLine();
                    lineIndex++;
                    sw.WriteLine(line);

                    if (lineIndex % lineOfEach == 0)
                    {
                        fileIndex++;
                        outputFile = Path.GetFileNameWithoutExtension(file) + "_" + fileIndex + ".csv";
                        sw.Flush();
                        sw.Close();

                        sw = new StreamWriter(outputFile, false, Encoding.UTF8);
                    }
                }
            }
        }

​

猜你喜欢

转载自blog.csdn.net/yuxuac/article/details/90053353