[英]How to add header and footer txt file in 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";
}
.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);
你的意思是:
string text = "header" + Environment.NewLine + "rest of file ... asjdhakjdh" + Environment.NewLine + "footer";
File.WriteAllText("filename.txt", text);
這樣可以節省
頭
文件的其余部分...... asjdhakjdh
頁腳
在名為filename.txt的.txt文件中
因此,您可以讀取文件,將其存儲在字符串中,添加頁眉和頁腳行,然后將其寫回到它所來自的同一文件中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.