【问题标题】:Splitting of text file not working properly in c#在 C# 中拆分文本文件无法正常工作
【发布时间】:2017-04-25 11:29:30
【问题描述】:

我需要写入文本文件。 如果文件大小超过 700MB,请创建新文件并写入。 我目前正在使用“|” 将数据从数据库分隔到文件,然后检查文件大小并拆分为多个文件,但文件splits 在行中间。 它应该写到行尾或在新文件中开始该特定行。

我需要在新拆分的文件的第一行写列名。

我是 C# 新手,能否请您通过示例代码向我推荐解决方案。

请在下面找到拆分文件的代码

 private static void ReadWriteToFile(string fileNames)
 {
     string sourceFileName = fileNames;
     string destFileLocation = Path.GetDirectoryName(fileNames);
     int index = 0;
     long maxFileSize = 700 * 1024 * 1024;
     byte[] buffer = new byte[65536];

     using (Stream source = File.OpenRead(sourceFileName))
     {
         while (source.Position < source.Length)
         {
             index++;

             string newFileName = Path.Combine(destFileLocation, Path.GetFileNameWithoutExtension(sourceFileName));
             newFileName += index.ToString() + Path.GetExtension(sourceFileName);
             using (Stream destination = File.OpenWrite(newFileName))
             {
                 while (destination.Position < maxFileSize)
                 {
                     int bytes = source.Read(buffer, 0, (int)Math.Min(maxFileSize, buffer.Length));
                     destination.Write(buffer, 0, bytes);

                     if (bytes < Math.Min(maxFileSize, buffer.Length))
                     {
                         break;
                     }
                }
            }
        }
    }
 }

提前致谢。

请告诉我是否有任何替代的最佳方法来做到这一点

【问题讨论】:

  • 逐行读写?

标签: c# asp.net file console-application


【解决方案1】:

试试这个,重写我在开始 c# 时代写的行文件拆分器。 (您只需将列标题作为字符串添加到新文件的开头。)

private static void SplitAfterMBytes(int splitAfterMBytes, string filename)
{
    // Variable for max. file size.
    var maxFileSize = splitAfterMBytes * 1048576;
    int fileCount = 0;
    long byteCount = 0;

    StreamWriter writer = null;

    try
    {
        var inputFile = new FileInfo(filename);
        var index = filename.LastIndexOf('.');
        //get only the name of the file.
        var fileStart = filename.Substring(0, index);
        // get the file extension
        var fileExtension = inputFile.Extension;

        // generate a new file name.
        var outputFile = fileStart + '_' + fileCount++ + fileExtension;
        // file format is like: QS_201101_321.txt.

        writer = new StreamWriter(outputFile);

        using (var reader = new StreamReader(filename))
        {
            for (string str; (str = reader.ReadLine()) != null;)
            {
                byteCount = byteCount + System.Text.Encoding.Unicode.GetByteCount(str);

                if (byteCount >= maxFileSize)
                {
                    // max number of bytes reached
                    // write into the old file, without Newline,
                    // so that no extra line is written. 
                    writer.Write(str);
                    // 1. close the actual file.
                    writer.Close();
                    // 2. open a new file with number incresed by 1.
                    outputFile = fileStart + '_' + fileCount++ + fileExtension;

                    writer = new StreamWriter(outputFile);
                    byteCount = 0; //reset the counter.
                }
                else
                {
                    // Write into the old file.
                    // Use a  Linefeed, because Write works without LF.
                    // like Java ;)
                    writer.Write(str);
                    writer.Write(writer.NewLine);
                }
            }
        }
    }
    catch (Exception ex)
    {
        // do something useful, like: Console.WriteLine(ex.Message);
    }
    finally
    {
        writer.Dispose();
    }
}

【讨论】:

  • writerreader 应该在 using statement 中声明。这确保即使抛出异常也能处理它们。
  • 在 Visual Studio 中尝试了您的编辑,它似乎有效。我没有在 writer 上使用 using 测试我的解决方案,但它看起来很奇怪,因为在 using 中创建了新的 writer。
  • 那是因为你不能重新分配你在using 语句中声明的变量,你会得到一个编译错误。如果你在 using 之外声明它,在 using 声明中使用它并重新分配它,你会收到一个警告。由于您需要重新分配writer,因此您最好关闭finally 块中的当前编写器。
  • 写这样一个“简单”的应用程序很有趣。 :D
  • 编写器的切换确实有点奇怪……也许应用程序可以重构为更简洁的设计。我会把它作为我年轻同事的练习;)
猜你喜欢
  • 2011-10-21
  • 2020-02-08
  • 1970-01-01
  • 1970-01-01
  • 2015-12-13
  • 1970-01-01
  • 2014-05-31
  • 1970-01-01
  • 2021-10-31
相关资源
最近更新 更多