我是一名初学C#程序员,并对我正在构建的应用程序提出了一个简短问题。我的进程读入多个文件,目的是根据文本文件中的1或0管道分隔字段剥离特定记录。它实际上是文件中最后一个分隔的字段。如果它是0,我将它写入一个临时文件(稍后将替换我读的原文),如果它不是我的东西。不要试图让它太混乱,但文件中有两种类型的记录,即标题行,然后是几行支持行。标题行是唯一具有标志的行,因此从下面可以看出,如果bool被设置为0的好记录,它会将标题记录与其下的所有supp记录一起写入,直到它遇到一个坏的一个在这种情况下它会否定写下他们,直到下一个好的。C#从字符串拆分中删除最后一个分隔的字段
但是,我现在想要做的(想知道最简单的方法)是如何在没有最后一个管道分隔字段(IE标志)的情况下编写标题记录。由于它应该始终是该行的最后2个字符(例如,需要先行管道时为“0 |”或“1 |”),它是否应该是我的inputrecord字符串上的字符串修剪?有更容易的方法吗?有没有办法在记录上进行拆分,但实际上并没有包含最后一个字段(在本例中是字段36)?任何意见,将不胜感激。谢谢你,
static void Main(string[] args)
{
try
{
string executionDirectory = RemoveFlaggedRecords.Properties.Settings.Default.executionDirectory;
string workDirectory = RemoveFlaggedRecords.Properties.Settings.Default.workingDirectory;
string[] files = Directory.GetFiles(executionDirectory, "FilePrefix*");
foreach (string file in files)
{
string tempFile = Path.Combine(workDirectory,Path.GetFileName(file));
using (StreamReader sr = new StreamReader(file,Encoding.Default))
{
StreamWriter sw = new StreamWriter(tempFile);
string inputRecord = sr.ReadLine();
bool goodRecord = false;
bool isheaderRecord = false;
while (inputRecord != null)
{
string[] fields = inputRecord.Split('|');
if (fields[0].ToString().ToUpper() == "HEADER")
{
goodRecord = Convert.ToInt32(fields[36]) == 0;
isheaderRecord = true;
}
if (goodRecord == true && isheaderRecord == true)
{
// I'm not sure what to do here to write the string without the 36th field***
}
else if (goodRecord == true)
{
sw.WriteLine(inputRecord);
}
inputRecord = sr.ReadLine();
}
sr.Close();
sw.Close();
sw = null;
}
}
string[] newFiles = Directory.GetFiles(workDirectory, "fileprefix*");
foreach (string file in newFiles)
{
string tempFile = Path.Combine(workDirectory, Path.GetFileName(file));
string destFile = Path.Combine(executionDirectory, Path.GetFileName(file));
File.Copy(tempFile, destFile, true);
if (File.Exists(destFile))
{
File.Delete(tempFile);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
finally
{
// not done
}
}
你可能分裂,使用链接的'拿(计数)'取除了最后一个字段,然后再次加入它来写出... – 2014-11-14 19:54:23