比如一个文本文档里有7行数据,将它每两行或者每三行等等分成多个新的文档
using System;
using System.Collections;
using System.IO;
using System.Text;
namespace ConsoleApplication1
{
public class Program
{
//变量 TotalCountInEveryFile 表示每个新建文档里的行数
private const int TotalCountInEveryFile = 3;
static void Main(string[] args)
{
ArrayList gotStrings = GetStreamMethod(“d:\\Hello.txt”);
Console.WriteLine(string.Join(“\n”, gotStrings.ToArray()));
if (gotStrings != null)
{
int fileCount = 1;
for (int i = 0; i < gotStrings.Count; i++)
{
StringBuilder sb = new StringBuilder();
sb.AppendFormat(“{0}\r\n”, gotStrings[i]);
if (i + 1 < gotStrings.Count)
{
i++;
}
else
{
WriteStreamMethod(string.Format(“d:\\Document{0}.txt”, fileCount), sb.ToString());
return;
}
while (i % TotalCountInEveryFile != 0)
{
sb.AppendFormat(“{0}\r\n”, gotStrings[i]);
if (i != gotStrings.Count – 1)
{
i++;
}
else
{
WriteStreamMethod(string.Format(“d:\\Document{0}.txt”, fileCount), sb.ToString());
return;
}
}
Console.WriteLine(sb.ToString());
WriteStreamMethod(string.Format(“d:\\Document{0}.txt”, fileCount), sb.ToString());
if (i % TotalCountInEveryFile == 0)
{
i–;
}
fileCount++;
}
}
}
// 读
private static ArrayList GetStreamMethod(string path)
{
ArrayList list = new ArrayList();
StreamReader sr = new StreamReader(path);
String line;
while ((line = sr.ReadLine()) != null)
{
list.Add(line.ToString());
}
return list;
}
//写
private static void WriteStreamMethod(string path, string content)
{
FileStream fs = new FileStream(path, FileMode.Create);
StreamWriter sw = new StreamWriter(fs);
sw.Write(content);
sw.Flush();
sw.Close();
fs.Close();
}
}
}