我需要使用此功能将标题添加到文本文件:
private static void WriteFile(string fileToRead, string fileToWrite, string mySearchString)
{
using (var sr = new StreamReader(fileToRead))
using (var sw = new StreamWriter(fileToWrite, true))
{
var count = 1;
while (sr.Peek() != -1)
{
var line = sr.ReadLine();
/* if (count == 3)
{
sw.WriteLine(line);
} */
if (count > 4)
{
if (line != null && line.Contains(mySearchString))
{
sw.WriteLine(line);
}
}
count++;
}
例如:将字符串“ blah blah blah”放在文本文件的顶部,而不会覆盖那里的文本。我需要在上面的函数内实现代码
请记住,我只希望标题写入一次。我正在使用此功能遍历多个文本文件并将其追加到新的文本文件中,但只需要一次写入标头,而不是每次打开文本文件进行解析时都需要写一次。
您的代码应如下所示:
using (var sr = new StreamReader(fileToRead))
using (var sw = new StreamWriter(fileToWrite, true))
{
if (sw.BaseStream.Position == 0)
sw.WriteLine("bla bla..."); // Only write header in a new empty file.
var count = 1;
祝您一切顺利。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句