如何使用Stream Writer写入文件开头? [英] how to write to beginning of file with Stream Writer?

查看:115
本文介绍了如何使用Stream Writer写入文件开头?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将我的字符串插入到文件的开头.但是在流编写器的开头没有附加功能.那我该怎么做呢?

I want to insert my string to the beginning of the file. But there is no function to append in beginning in stream writer. So how should I do that ?

我的代码是:

string path = Directory.GetCurrentDirectory() + "\\test.txt";
StreamReader sreader = new StreamReader(path);
string str = sreader.ReadToEnd();
sreader.Close();

StreamWriter swriter = new StreamWriter(path, false);

swriter.WriteLine("example text");
swriter.WriteLine(str);
swriter.Close();

但它似乎没有优化.那么还有什么办法吗?

But it doesn't seem optimized. So is there any other way ?

推荐答案

你就快到了:

        string path = Directory.GetCurrentDirectory() + "\\test.txt";
        string str;
        using (StreamReader sreader = new StreamReader(path)) {
            str = sreader.ReadToEnd();
        }

        File.Delete(path);

        using (StreamWriter swriter = new StreamWriter(path, false))
        {
            str = "example text" + Environment.NewLine + str;
            swriter.Write(str);
        }

这篇关于如何使用Stream Writer写入文件开头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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