通过使用streamwriter,C#正确地将标头添加到输出文本文件 [英] Adding header to the output text file correctly, by using streamwriter, C#

查看:294
本文介绍了通过使用streamwriter,C#正确地将标头添加到输出文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望在读取和写入指定条件后将标题添加到输出文本文件中。



我的代码从输入文件中读取并写入输出文件:

Ana老师256

Ben学生12



i想要添加标题和输出文件:

用户功能点

Ana老师256

Ben学生123



我试图读取文件并用新行(标题)重写它。



我尝试过:



I want to add header to the output text file, after reading and writing with a specified condition.

My code reads from input file and writes to the output file:
Ana Teacher 256
Ben Student 12

i want to add header and output file to be:
User Function Points
Ana Teacher 256
Ben Student 123

I tried to read the file and rewrite it with a new line(header).

What I have tried:

string path2 = path + @"\new.txt";
 string s;
 string header = (User, Function, Points);
 string tempfile = path2 + "\\tempfile.txt"; 
//part of code for stream reader, i am not including here

using (StreamWriter writer = new StreamWriter(path))
            {
                 writer.WriteLine(l);

static void InsertHeader(string path2, string header)
{
    var tempfile = Path.GetTempFileName();
    using (var writer = new StreamWriter(tempfile))
    using (var reader = new StreamReader(path2))
    {
        writer.WriteLine(header);
        while (!reader.EndOfStream)
            writer.WriteLine(reader.ReadLine());
    }
    File.Copy(tempfile, path2, true);
    File.Delete(tempfile);
}

 label2.Text = "File is converted ";

}

推荐答案

您没有在方法内定义方法,也无法打开流编写器打开文件,你不能覆盖正在读取的文件。



作为建议,使用File.ReadAllText读取整个文件,然后将标题文本添加到该文本中,并将其写回原始文件:

You don't define methods inside methods, and you can't open a stream writer on an open file, and you can't overwrite a file that is being read.

As a suggestion, use File.ReadAllText to read your whole file, then add your header text to that, and write it back over the original file:
string path = @"D:\Temp\MyFile.txt";
string data = File.ReadAllText(path);
string withHeader = "The header\n" + data;
File.WriteAllText(withHeader);


这篇关于通过使用streamwriter,C#正确地将标头添加到输出文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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