简体   繁体   English

在C#中更新文本文件

[英]update a text file in C#

I have a text file. 我有一个文本文件。 I need to find some data and update some data. 我需要查找一些数据并更新一些数据。 Let me explain it with an example. 让我用一个例子来解释它。 This is my text file: 这是我的文本文件:

NAME:Date
VALUE:02/03/2011
NAME:NoOfPages
VALUE:250
…
…
…
…
Total_Size:45725

I need to update 250 and 45725 values. 我需要更新250和45725值。 So Im looking to do it using Regular Expression. 因此,我希望使用正则表达式来做到这一点。 Is it the best way to do that or is there any better method to do this. 是执行此操作的最佳方法,还是有更好的方法来执行此操作? Can anyone can help to do it. 任何人都可以帮忙做到这一点。

Im using C# and VS 2008. My application is windows based application. 我正在使用C#和VS2008。我的应用程序是基于Windows的应用程序。

From looking at the sample I would say a line-based approach might be just as easy. 通过查看样本,我会说基于行的方法可能同样简单。

Just read a line and check StartsWith 只需阅读一行并检查StartsWith

I would not use regex in your case. 我不会在您的情况下使用正则表达式。 It seems to be a short name:value list. 它似乎是一个简短的name:value列表。

I would suggest using a state variable. 我建议使用state变量。

  1. Read line by line. 逐行读取。
  2. Split using : character. 使用:字符Split
  3. Make a switch statement on the first part of the split. 在拆分的第一部分做一个switch语句。
    • if it is NAME then store the second part in the state value. 如果是NAME则将第二部分存储在状态值中。 Write the line. 线。
    • if it is VALUE then 如果它是VALUE
      • if the state value correspond to a field you must update: write the line with the new value. 如果state值对应于一个字段,则必须更新:用写入行。
      • else write the line as is. 否则按原样编写该行。
  4. Loop to 1 until EOF 循环到1,直到EOF

Would it be possible in your case? 您的情况可能吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM