在c#中创建,检查,更新文本文件? [英] Create, check, update text file in c#?

查看:106
本文介绍了在c#中创建,检查,更新文本文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的文本文件结构如下:

I have this text file structured like this:

ID1|PROJECT1|STATION1|LOCKED
ID2|PROJECT2|STATION2|RELEASED
ID3|PROJECT3|STATION3|RELEASED
ID4|PROJECT4|STATION1|LOCKED



我想要做的是:检查文件是否存在,如果没有创建它并在其中添加数据(完成) ),否则如果它已经存在,看看特定站点上的某个ID和PROJECT是否被释放或锁定(如果它被释放)做了什么,如果它被锁定则更新文件并使其释放,如果不是以上添加ID | PROJECT | STATION | RELEASED在文件中。我需要对现有ID | PROJECT | STATION进行更新,而不在文件中创建任何重复项并仅添加一次。我尝试过一些东西,但似乎都没有用。关于如何更新文件中的现有行而不创建重复项以及文件中是否存在该行以添加它的任何建议?


What i want to do is to: check if file exists, if not create it and add the data in it(done), else if it already exists see if some ID and PROJECT on a specific station is released or locked if it is released do something and if it's locked update the file and make it released, AND if non of the above add ID|PROJECT|STATION|RELEASED in the file. I need to do the update on existing ID|PROJECT|STATION without creating any duplicates in the file and adding them only once. I've tried a few things but none seem to work. Any suggestion on how i could update existing lines in file without creating duplicates and if the line does not exists in file to add it?

推荐答案

没有自动方式这样做 - 文本文件没有结构化,所以没有你真正可以使用的帮助软件。

你可以相当容易地做到:只需将所有行读成一个字符串数组,将每个行分开|字符并根据您想要的数字检查各个部分。然后修改相应的行,并将它们全部写回。但它有点麻烦 - 如果你可以改变文件格式,那么使用XML会让你更像是一个数据库而只更新你感兴趣的行。(它基本上会做读取 - 修改 - 写入的东西对于你在幕后)取决于你想要处理的ID和项目的可能数量。
There is no automatic way to do that - text files aren't structured so there is no "helper" software you can really use.
You can do it fairly easily: just read all the lines into a string array, split each on the '|' character and check the individual sections against the numbers you want. Then modify the appropriate line, and write them all back. But it's a bit cumbersome - if you can change the file format, then using XML would let you treat it more like a database and update only the "row" you are interested in. (It would basically do the read-modify-write stuff for you behind the scenes) Depends I guess on the likely number of IDs and Projects you expect to handle.


你应该解析输入文件以获得相关的数据并将其存储在合适的数据结构中。例如,您可以使用元组字典(请参阅此 Stack Overflow 问题:复合词典词典 [ ^ ])它会自动处理你的唯一性要求。
You should parse the input file for getting the relevant data and store it in a suitable data structure. You may, for instance use a dictionary of tuples (see this Stack Overflow question: Composite Key Dictionary[^]) it would automatically handle the uniqueness requirement for you.


这篇关于在c#中创建,检查,更新文本文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆