替换文件中的文本 [英] Replacing text in a file

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

问题描述



我有一个文件,必须替换文件中的某些文本.我使用下面的代码来更改文本.

Hi,

I have a file where i have to replace a certain text inside a file. I used below code to change th text.

string path = "C:\\Documents and Settings\\Desktop\\sample.txt";
StreamReader reader = new StreamReader(path);
string text = reader.ReadToEnd();
text = text.Replace("9C39C270-C77F-11DE-92BB-00188B8DE4BE", "asdfgh");
reader.Close();
File.Delete(path);
StreamWriter stream = new StreamWriter(path);
stream.Write(text);
stream.Close();

一切正常.但是我感觉到,它会影响性能,因为它使用了许多操作,例如
以读取模式打开文件,复制文本,关闭文件,删除文件,创建新文件并写入文件.

还有其他选择,这样我可以一次完成所有操作吗?


Sab

This is working fine. But what I feel is, it affects the performance because it uses lot of operations like
opening the file in read mode, copying the text, Closing the file,  deleting the file, Create a new file and writing into the file.

Is there any other alternative for this so that I can do all the operations in a single shot?


Sab

推荐答案

据我所知,您不需要删除文件,只需使用StreamWriter打开它,它将覆盖文件正文.
这是简单的改进.也许还有其他选择.
As I know you don't need to delete file, just open it with StreamWriter and it will override file body.
This is simple improving. Maybe exists some other alternative.


这篇关于替换文件中的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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