【发布时间】:2018-02-05 17:00:23
【问题描述】:
如何在删除特定行后根据特定行的条件 xyz=true 将文本文件行移动一格。我想使用 C#。
using (StreamWriter writer = new StreamWriter(file))
{
while ((line = rows[rowIndex++]) != null)
{
if( line contains xyz )// i know the logic to find this;
{
delete this line and shift all below lines one up;
}
}
}
【问题讨论】:
-
安全的做法是将未删除的行写入临时文件,如果一切正常,将临时文件与原始文件交换,然后删除旧文件。 Here is an example。如果您在更改过程中遇到 IO 错误,则不这样做可能会损坏您的文件。
-
File.WriteAllLines(filePath, File.ReadAllLines(filePath).Where(line => !line.Contains("xyz")));(这应该可以,但请考虑 @DourHighArch 关于安全处理 I/O 错误的评论)