首页 \ 问答 \ 将标题追加到文本文件[重复](Append header to text file [duplicate])

将标题追加到文本文件[重复](Append header to text file [duplicate])

这个问题在这里已有答案:

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

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”放在文本文件的顶部,而不覆盖那里的文本。 我需要在上面的函数中实现代码

请记住,我只想写一次标题。 我正在使用此函数迭代多个文本文件并附加到新的文本文件,但只需要一次写入标题,而不是每次打开文本文件进行解析。


This question already has an answer here:

I need to add a header to a text file using this function:

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++;
            }

For example: put the string "blah blah blah" to the top of the text file without overwriting the text that is there. I need the code to be implemented inside the function above

Keep in mind I only want the header written once. I am iterating through multiple text files using this function and appending to a new text file but only need the header written one time not everytime a text file is opened for parsing.


原文:https://stackoverflow.com/questions/20790288
更新时间:2019-06-20 00:57

最满意答案

您的代码应如下所示:

    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;

祝你好运。


You code should look like this:

    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;

Good luck with your quest.

2013-12-26

相关问答

更多

文本文件解释[重复](Text file interpretation [duplicate])

你可以在4个python的东西上谷歌(或者只读官方的python文档) - 例如文件,字符串,字典和列表,最后会有几行python代码来处理它。 因为这看起来像是学习一些python的任务...... 如果您真的想学习,请为您考虑最佳解决方案 - 只需拆分任务并按步骤执行,例如,您需要: 从文件中读取数据 解析行(拆分名称和分数) 将它存储在某个地方,例如在名称为键的python字典中,以及作为值的python列表。 例如: scores['Bob'] == [8, 8, 7]看起来容易理解和简单 ...

在特定行阅读文本文件[复制](Read text file at specific line [duplicate])

这是一个解决方案,它将文件迭代两次(第一次计算行数,下次选择行数)。 好处是您不需要在内存中创建3000个字符串的数组。 但是,如上所述,它可能会变慢。 为什么可能? - 因为File.ReadAllLines在里面创建了一个字符串列表,并且该列表将被多次调整大小,同时填充3000个项目。 (初始容量为4 ,当内部数组完全填充时,将创建新的加倍大小的数组,并且所有字符串将被复制到那里)。 所以,该解决方案使用File.ReadLines方法,它返回IEnumerable<string>的行和跳过你 ...

如何在不覆盖文件内容的情况下写入文本文件?(How to write to a text file without overwriting the contents of the file? [duplicate])

首先,您应该在NSMutableArray中读取文件的内容,然后将数据附加到数组,并再次将其写入文件。 Firstly, you should read the contents of the file in a NSMutableArray, then append your data to your array, and write it to the file again.

使用C#从文本文件中读取最后一个符号[复制](Reading last symbol from text file using C# [duplicate])

如果文件不是太大 ,只需读取这些行并选择最后一行: string lastLine = File.ReadLines("pathToFile").LastOrDefault(); // if the file is empty 所以你用这种方式得到最后一个字符: Char lastChar = '\0'; if(lastLine != null) lastChar = lastLine.LastOrDefault(); File.ReadLines在开始处理之前不需要读取所有行,所以它在内存 ...

将LINQ结果写入文本文件(Writing a LINQ result into a text file)

可能的解决方案如下所示: var result = from c in census_data group c by c.state into g join s in state_gdp on g.FirstOrDefault().state equals s.state orderby s.gdp descending select new { State = g.Key, Count = g.Count(), ...

C:将文本文件中的数据添加到单个链接列表中(C: Adding data from text file into a singly linked list)

尝试: temp->data = strdup(line); 复制(复制)什么行指向。 否则,每一行都指向buffer ,每个新行都会被覆盖。 Try: temp->data = strdup(line); to duplicate (make a copy of) what line points at. Otherwise every line points at the buffer which is getting overwritten with each new line.

在python上通过互联网阅读文本文件(Read text file over internet on python)

>>> from urllib2 import Request, urlopen >>> url = 'http://hughchalmers.com/example.txt' >>> urlopen(Request(url=url, headers={'User-Agent': "hey, it's wim"})).read() 'Exmaple Text' >>> from urllib2 import Request, urlopen >>> url = 'http://hughchalm ...

打开二进制文件与文本之间的区别[复制](Difference between opening a file in binary vs text [duplicate])

你给出的链接确实描述了不同之处,但是它隐藏在页面的底部: http://www.cplusplus.com/reference/cstdio/fopen/ 文本文件是包含文本行序列的文件。 根据应用程序运行的环境,文本模式下的输入/输出操作可能会发生一些特殊字符转换,以适应系统特定的文本文件格式 。 虽然在某些环境下不会发生转换,并且文本文件和二进制文件的处理方式相同,但使用适当的模式可以提高可移植性。 转换可能是将\r\n规范化为\n (反之亦然),或者可能忽略0x7F以外的字符(FTP中的a- ...

相关文章

更多

最新问答

更多
  • Android宽度:100%修复(网站接管问题)(Android width:100% fix (website takeover issue))
  • C ++函数/方法设计的良好实践(Good practice in C++ function/method design)
  • 计算其他表中不存在的所有记录 - SQL查询(Count all records that does not exist to other table - SQL Query)
  • 为什么我要用JPA共享ID?(Why do I get shared Ids with JPA?)
  • asp.net - 如何显示来自html格式的数据行的字段(asp.net - how to display a field from data row that is in html format)
  • 我们如何使用ActiveRecord从连接表中删除行?(How can we delete rows from a join table by using ActiveRecord?)
  • ng-class搞乱了类的顺序(ng-class messing with the order of classes)
  • oracle 12g无效数字错误(oracle 12g invalid number error)
  • 更改ng-src值onclick(Change ng-src value onclick)
  • 如何在android中自动添加自定义依赖项以创建新项目?(How to add custom dependencies automatically in android for ever a new project is created?)
  • datetime函数在PHP中(datetime function in php)
  • 在javascript中获取会话数组的值(in javascript get the value of a session array)
  • 如何在UTF8中编译LaTeX?(How can I compile LaTeX in UTF8? [closed])
  • Rspec:“array.should == another_array”,但不用担心订单(Rspec: “array.should == another_array” but without concern for order)
  • Logcat错误:无法在android片段中加载视图(Logcat error: unable to load view in android fragments)
  • JavaFX的。(JavaFX. Adding items to the list in different threads is not working)
  • 从GDATA日历资源迁移到Google Calendar Resource api(Migrate from GDATA calendar resource to Google Calendar Resource api)
  • SSRS 2008 - 以零情景处理分割(SSRS 2008 - Dealing with division by zero scenarios)
  • 我如何以编程方式添加一个listView列标题的点击事件(How can I add a listView column header a click event programmatically)
  • Wxpython:无法检索有关列表控件项XXX的信息(Wxpython: Couldn't retrieve information about list control item XXX)
  • 使用Tortoise SVN在SVN存储库中移动目录(Move Directory across SVN repository using Tortoise SVN)
  • 天蓝色服务结构集群中的web api无状态服务是否在一段时间不活动后进入休眠状态?(Do web api stateless services in azure service fabric cluster go to sleep after a period of inactivity?)
  • 我可以设置intelliJ来突出显示PHP编码风格吗?(Can I set intelliJ to highlight php coding style?)
  • 用javafx创建一个Truetype字体文件(Creating a Truetype Font file with javafx)
  • Spring ftp配置错误(Spring ftp configuration is wrong)
  • 使用gsub去除多个字符(Using gsub to strip multiple characters)
  • 续订推送证书并保持当前的App Store App正常工作(Renew Push certificate and keep current App Store App working)
  • js:ES5和ES6之间关于'this'关键字用法的一个令人困惑的观点(js: one confusing point about 'this' keyword usage between ES5 and ES6)
  • window.onload vs $(document).ready()(window.onload vs $(document).ready())
  • 在Swift中,如何声明一个符合一个或多个协议的特定类型的变量?(In Swift, how can I declare a variable of a specific type that conforms to one or more protocols?)