如何在C#中添加页眉和页脚txt文件?

时间:2016-06-23 12:33:30

标签: c#

我想在文本文件中添加页眉和页脚。我怎样才能做到这一点?我的目标应该是这样的:

 tr.AddHeaderAndFooter("Header","footer";

例如:

using (var fileStream = new FileStream(ConfigurationManager.AppSettings["TargetDir"] + swiftFile, FileMode.Open, FileAccess.Read))
{
    TextReader tr = new StreamReader(fileStream);
    tr.AddHeaderAndFooter("Header","footer";
}

2 个答案:

答案 0 :(得分:3)

.txt文件没有页眉或页脚。
但您可以使用以下代码示例模拟此行为:

// since there is no predefined method to add a string into the beginning   
// of a file, you have to first read the whole file content into a temporary 
// variable
string currentContent = String.Empty;
if (File.Exists(filePath))
{
    currentContent = File.ReadAllText(filePath);
}

// now you can put your header into the beginning of the file so:
string header = "My Header";
File.WriteAllText(filePath, header + Environment.NewLine + currentContent );

// and finally you use the append method to add footer to the end of the file
string footer = "My Footer";
File.AppendAllText(filepath, Environment.NewLine + footer);

答案 1 :(得分:0)

你的意思是:

string text = "header" + Environment.NewLine + "rest of file ... asjdhakjdh" + Environment.NewLine + "footer";
File.WriteAllText("filename.txt", text);

这将保存

  

     

其余文件...... asjdhakjdh

     

页脚

在名为 filename.txt的 .txt 文件中

因此,您可以读取文件,将其存储在字符串中,添加页眉和页脚行,然后将其写回到它所来自的文件中。