c# - 将文件的一部分移动到另一个文件

标签 c# .net algorithm

<分区>

我有几行文件:

Lines1

Lines2

Lines3

....

LinesN

我有以下代码:

我的代码

while ((line = streamReader.ReadLine()) != null)
{ 
    var str = GetData(line);
    if(str == "Fatal Error")
    {
    }
}    

GetData 期间,我可以抛出一些异常。在这种情况下,我想将剩余的行移动到另一个文件。我该怎么做?
我应该声明 positionCount 吗?还是有更聪明的方法?

最佳答案

您可以简单地从检测到错误的地方继续,即:

while ((line = streamReader.ReadLine()) != null)
{ 
    var str = GetData(line);
    if(str == "Fatal Error")
    {
        WriteRemainingLines(line, streamReader);
        break;
    }
}  

line 参数将包含包含错误的行:

public void WriteRemainingLines(string line, streamReader reader)
{
    using (var targetfile = ...)
    {
        do
        {
            targetfile.WriteLine(line);
        }
        while ((line = reader.ReadLine()) != null);
    }
}

关于c# - 将文件的一部分移动到另一个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48827559/

相关文章:

C#线程问题

c# - razor 中的 for 循环创建输入标签列表

java - 雅各布 com.jacob.com.ComFailException : Can't map name to dispid:

algorithm - 在基于类(class)中心的模糊化算法中如何计算决策属性的类(class)中心?

查找满足一组条件的数字序列的算法

c# - 创建弹出气球,如 Windows Messenger 或 AVG

c# - 取消由 ASP.NET 启动的任务

asp.net - 如何在WPF 4.0中调用Web API

.net - EF 代码优先 : Methods that can translate to SQL

algorithm - 微服务和发布状态与状态变化