将整个内容写入文件的问题 [英] Issue with writing entire contents to file

查看:44
本文介绍了将整个内容写入文件的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我的代码,它只保留文件的最后一行,而不是整个内容。不确定我缺少什么感谢任何建议。



Hello below is my code and it keeps writing only the last line to the file and not the entire contents. Not sure what I am missing appreciate any suggestions.

var dom = new CQ(textFile);
dom["tbody"].ToList().ForEach(idNumber =>
var tableRow = new CQ(idNumber.InnerHTML)["tr"].ToList();

      tableRow.ForEach(row =>
      {
         var tdElements =  new CQ(row.OuterHTML)["td"].Text();


      listOfConMet.Add(new Fields()
      {
        idNumber = tdElements


      });
             Console.WriteLine(tdElements);
          File.WriteAllText(@"C:\data.txt", tdElements);
      });
  });

推荐答案

那么,你期待什么?

File.WriteAllText重新创建文件每次调用它 - 并且因为你为表中的每一行调用它,只有在ForEach完成后才会保存最后处理的行 - 所有其他行将被丢弃。



就个人而言,我设置了一个StringBuilder并将每行的数据附加到该行,然后在循环完成后再执行一个WriteAllText。
Well, what do you expect?
File.WriteAllText create the file afresh every time you call it - and since you call it for each row in your table, only the last processed row will actually be saved once the ForEach has been completed - all the others will be thrown away.

Personally, I'd set up a StringBuilder and Append each row's data to that, then do a single WriteAllText after the loop has been finished.


我不要我不知道你的代码在做什么,也没有什么问题,但我知道如何知道。

调试器是你的朋友。

学会使用调试器,你会看看你的代码是一步一步执行的,在代码执行时检查变量。

原则是检查代码是否正在执行预期的操作,从而缩小了地方的位置搜索错误。

次要效果,这是一种宝贵的学习方式哪些有效,哪些无效。
I don't know what your code is doing nor what is wrong, but I know how to know.
the debugger is your friend.
Learn to use the debugger and you will see your code executing step by step, inspect the variable as the code is executing.
The principle is to check if the code is doing what it is expected to do or not, thus narrowing the places where to search for bugs.
secondary effect, it is an invaluable way to learn what works and what don't.


这篇关于将整个内容写入文件的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆