【发布时间】:2023-07-18 11:51:02
【问题描述】:
我是一名初学者 c# 程序员,对我正在构建的应用程序有一个简短的问题。我的过程读取多个文件,目的是根据文本文件中的 1 或 0 管道分隔字段去除特定记录。它实际上是文件中的最后一个分隔字段。如果它是 0,我将它写入一个临时文件(稍后将替换我读取的原始文件),如果它是其他任何东西我不这样做。不要试图让它太混乱,但文件中有两种类型的记录,一个标题行,然后是一些支持行。标题行是唯一具有标志的行,因此您可以从下面看出,如果 bool 通过为 0 设置为良好记录,它会将标题记录连同其下方的所有 supp 记录一起写入,直到遇到错误在这种情况下,它将否定写入它们,直到下一个好的。
但是,我现在要做的(并且想知道最简单的方法)是如何在没有最后一个管道分隔字段(即标志)的情况下编写标题记录。由于它应该始终是该行的最后 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
}
}
【问题讨论】:
-
您可以拆分,使用链接的
Take(count)获取除最后一个字段之外的所有字段,然后再次加入以写出...
标签: c# string streamreader streamwriter