在文本文件中查找和编辑行

时间:2015-05-16 05:27:28

标签: c# file edit streamwriter

我怎样才能找到特定的图书ID,ex = 11(带\t+图案)

book ID\t   Book Titlte\t       Author\t              Edition\t   DueDate\t   Borrower ID\n   
    10\t    Java Performance\t  Charlie Hunt, Binu John\t   1\t -\t -\n
    11\t    Java Puzzlers: Traps, Pitfalls, and Corner Cases\t  Joshun Bloch, Neal Gafter\t 1\t 23/04/2015\t    100002\n     //// this one
    12\t    Real-Time C++\t Chris Kormanyos\t   1\t 23/05/2015\t    100020\n
    13\t    Secure Coding in C and C++\t    Robert Seacord\t    2\t -\t -

DueDate和借款人ID变为“ - ”

book ID\t   Book Titlte\t       Author\t              Edition\t   DueDate\t   Borrower ID\n   
    10\t    Java Performance\t  Charlie Hunt, Binu John\t   1\t -\t -\n
    11\t    Java Puzzlers: Traps, Pitfalls, and Corner Cases\t  Joshun Bloch, Neal Gafter\t 1\t -\t -\n ///////////became this one 
    12\t    Real-Time C++\t Chris Kormanyos\t   1\t 23/05/2015\t    100020\n
    13\t    Secure Coding in C and C++\t    Robert Seacord\t    2\t -\t -\n

1 个答案:

答案 0 :(得分:1)

总有很多方法可以做到这一点,所有这些都完全取决于问题的背景。一个非常简单(天真?)的方式如下:

 var idToFind = 11;
 var s = File.ReadAllText(fPath);
 var start = s.IndexOf(Environment.NewLine + idToFind.ToString() + '\t');
 var end = s.IndexOf(Environment.NewLine, start + 1);
 var line = s.Substring(start, end - start);
 var lineFields = line.Split("\t".ToCharArray());
 lineFields[4]= "-";
 lineFields[5]= "-";
 var newContent = s.Replace(line, lineFields.Join("\t"));
 File.WriteAllText(fPath, newContent);