c# - 将标题附加到文本文件

标签 c# .net io

<分区>

我需要使用此函数向文本文件添加标题:

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;

祝你任务顺利。

关于c# - 将标题附加到文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20790288/

相关文章:

C#/WinAPI - 监视内存区域

.net - 为什么即使页面的 EnableSessionState ="False"ASP.NET 仍然访问状态服务器,但仅适用于 VB.NET 站点,而不适用于 C# 站点?

python - 如何使用 Python io 模块构建内存驻留数据结构?

c# - 意外的钻石方形算法结果

c# - 像实时新闻提要ajax刷新一样实现facebook?

c# - 使用 List.Move 将项目移动到列表底部

javascript - 在 TypeScript 中使用关键字正则表达式获取字符串的一部分

c# - Icecast 2 : protocol description, 使用 C# 流式传输到它

c# - 如何在 .NET 中远程逐行读取文件?

java - 导入 .dat 文件 Java