如何同时读取和写入文本文件. [英] How to read and write Text file at the same time.

查看:84
本文介绍了如何同时读取和写入文本文件.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,
如何同时读取和写入文本文件.

我有以下代码,但问题是它确实写在文件内容的末尾.但我希望它写在两个"之后.即,如果读取的行包含两个",则在两个"之后写测试".

Hello,
How can i read and write a text file at the same time.

I have the following code but the problem is that it does writes at the end of the file contents. but i want it to write at after "two". i.e. if the read line contains "two" then write "test" after "two".

FileStream fsrw = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite);
StreamReader sr = new StreamReader(fsrw);
StreamWriter sw = new StreamWriter(fsrw);
test = "Dummy";

 while (test != null)
{
 if (test.Contains("two"))
    {
    sw.Write("test");
    }
    test = sr.ReadLine();
}
sw.Close();
}

推荐答案

读取同时被编辑的文件听起来是个坏主意.

恐怕您会得到意想不到的结果和无法发现的错误...

想象以下情况:

StreamWriter默认情况下将数据写入流的末尾,因此单词"test"很可能会出现在文件末尾.也许可以强制StreamWriter在任意位置开始写入,但这并不能解决整个问题...您将不得不跟踪当前位置,考虑到文件为随时间变化.并且不要忘记StreamReaderStreamWriter都使用缓冲区有效地加载/写入数据,这增加了更多的复杂性...

我建议先读取整个文件,然后进行更改,然后再写入文件(或者,如果速度很重要,请在读取或写入时即时执行更改).如果文件太大,请使用临时文件,但不要同时读写...
Reading a file that is being edited at the same time sounds like a really bad idea.

I''m afraid you could get unexpected results and impossible-to-find bugs...

Imagine the following scenario:

StreamWriter writes data to the end of the stream by default so the word "test" would most probably appear at the end of the file. Maybe it is possible to force StreamWriter to start writing at an arbitrary location, but that would not solve the whole problem... You would have to keep track of the current position, which is pretty difficult considering the fact that the file is changing in time. And don''t forget that both StreamReader and StreamWriter use buffers to load/write data efficiently, which is adds even more complexity...

I suggest reading the entire file first, perform the changes and then write the file (or, if speed is important, perform the changes on the fly while reading or writing). If the file is too large, use a temporary file, but do not read and write at the same time...


这篇关于如何同时读取和写入文本文件.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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