如何编辑文本文件的特定行 [英] how to edit specific line of a text file

查看:96
本文介绍了如何编辑文本文件的特定行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

朋友们。



i想在我的应用程序启动路径中编辑文本文件的第4行。



我该怎么做。我搜索了更多但是有替换文本文件的所有行中的单词的解决方案。



谢谢。

解决方案

基本上,你需要读取所有文件,修改它然后全部写完。这是因为您修改可以更改行的长度,这意味着由于移位,下面的所有内容都将被重写。在最简单的情况下,您可以使用:

http ://msdn.microsoft.com/en-us/library/s2tte0y1(v = vs.110).aspx [ ^ ],

http://msdn.microsoft.com/en-us/library/bsy4fhsa(v=vs.110).aspx [ ^ ],

http:// msdn .microsoft.com / zh-CN / library / 92e05ft3(v = vs.110).aspx [ ^ ],

http://msdn.microsoft.com/en-us/library/3det53xh(v = vs.110)的.aspx [<啊ref =http://msdn.microsoft.com/en-us/library/3det53xh(v=vs.110).aspx\"target =_ blanktitle =New Window> ^ ]。



如果文件太大,则必须逐行创建临时文件和读/写,最后将临时文件重命名为名称原文:

http://msdn.microsoft.com/en-us/library/system.io.file.move%28v=vs.110%29.aspx [ ^ ]。br />


-SA


替代方法是:忘记那些自制的操作并做一些有教养的事情,例如基于XML的序列化。最好和(迄今为止)最简单的方法是数据合同。请参阅: http://msdn.microsoft.com/en-us/library/ms733127.aspx [ ^ ]。



您无关:序列化程序将您的数据模型(整个对象图,如果您愿意)存储到XML文件或流中,并在需要时将其还原回内存。请参阅我过去的答案,我提倡这种方法:

创建属性文件...... [ ^ ],

如何在表单应用程序中使用XML文件编写器和阅读器? [ ^ ]。



< DD> -SA

hi friends.

i want to edit line 4 of a textfile in my application startup path.

how can i do that.i searched more but there is solutions for replacing words that are in the all line of textfile.

thanks.

解决方案

Basically, you need to read all the file, modify it and then write it all. This is because you modification can change the length of the line, and it means that all the content below will be rewritten due to the shift. In simplest case, you could use:
http://msdn.microsoft.com/en-us/library/s2tte0y1(v=vs.110).aspx[^],
http://msdn.microsoft.com/en-us/library/bsy4fhsa(v=vs.110).aspx[^],
http://msdn.microsoft.com/en-us/library/92e05ft3(v=vs.110).aspx[^],
http://msdn.microsoft.com/en-us/library/3det53xh(v=vs.110).aspx[^].

If a file is too big, you will have to create a temporary file and read/write line by line, and, at the end, rename temporary file to the name of original one:
http://msdn.microsoft.com/en-us/library/system.io.file.move%28v=vs.110%29.aspx[^].

—SA


Alternative approach would be: forget those home-baked manipulations and do something cultured, such as XML-based serialization. The best and (by far) simplest way to do that is Data Contract. Please see: http://msdn.microsoft.com/en-us/library/ms733127.aspx[^].

You have nothing to do: the serializer stores you data model (whole object graph, if you will) to an XML file or stream and restore it back to memory when needed. Please see my past answers where I advocate this approach:
Creating property files...[^],
How can I utilize XML File streamwriter and reader in my form application?[^].

—SA


这篇关于如何编辑文本文件的特定行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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