C#正确地将标头添加到输出文本文件

C#正确地将标头添加到输出文本文件

本文介绍了通过使用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 ";

}

推荐答案

string path = @"D:\Temp\MyFile.txt";
string data = File.ReadAllText(path);
string withHeader = "The header\n" + data;
File.WriteAllText(withHeader);


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

09-03 14:27