我已经使用以下代码使用“ / *”作为分隔符将一个大型文本文件拆分为许多较小的文件。
这可以按预期工作,但是我现在正在寻找从每个较小的新文本文件中提取文本的第一行,并使用它分别命名每个文件,而不是“ C:\ output-files- { 0} .txt”,C:\ output-files- {1} .txt ...等等
请问有人可以帮忙吗?
非常感谢。
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Running file splitter now...");
Splitter splitter = new Splitter();
splitter.Split("C:\\STA_PRD_allJobs.JIL", "C:\\output-files-{0}.txt");
Console.WriteLine("JIL script splitting complete.");
}
}
class Splitter
{
public void Split(string inputfile, string outputfilesformat)
{
int i = 0;
System.IO.StreamWriter outfile = null;
string line;
try
{
using (var infile = new System.IO.StreamReader(inputfile))
{
while (!infile.EndOfStream)
{
line = infile.ReadLine();
if (line.Contains("/*"))
{
if (outfile != null)
{
outfile.Dispose();
outfile = null;
}
}
if (outfile == null)
{
outfile = new System.IO.StreamWriter(
string.Format(outputfilesformat, i++),
false,
infile.CurrentEncoding);
}
outfile.WriteLine(line);
}
}
}
finally
{
if (outfile != null)
outfile.Dispose();
}
}
}
答案 0 :(得分:0)
您可以阅读第一行并将其存储在变量中。
public void Split(string inputfile, string outputfilesformat)
{
int i = 0;
System.IO.StreamWriter outfile = null;
string line;
try
{
var firstLine = string.Empty;
using (var infile = new System.IO.StreamReader(inputfile))
{
while (!infile.EndOfStream)
{
line = infile.ReadLine();
if(string.IsNullOrEmpty(firstLine))
firstLine = line;
if (line.Contains("/*"))
{
if (outfile != null)
{
outfile.Dispose();
outfile = null;
}
}
if (outfile == null)
{
outfile = new System.IO.StreamWriter(
$"{firstLine}.txt",
false,
infile.CurrentEncoding);
firstLine = string.Empty;
}
outfile.WriteLine(line);
}
}
}
finally
{
if (outfile != null)
outfile.Dispose();
}
}