【发布时间】: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