本文介绍了附加在C#的文本文件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正尝试从C#编写txt文件,如下所示:
I am trying to write a txt file from C# as follows:
File.WriteAllText("important.txt", Convert.ToString(c));
File.WriteAllLines("important.txt", (from r in rec
select r.name + " " + r.num1 + " " + r.num2 + " " + r.mult + " " + r.rel).ToArray());
但是第二个File.WriteAllLines会覆盖文件中的第一个条目.有什么建议我该如何追加数据?
But the second File.WriteAllLines overrides the first entry in the file. Any suggestion how can I append data?
推荐答案
您应使用 File.AppendAllLines
,如下所示:
File.WriteAllText("important.txt", Convert.ToString(c));
File.AppendAllLines("important.txt", (from r in rec
select r.name + " " + r.num1 + " " + r.num2 + " " + r.mult + " " + r.rel).ToArray());
System.IO.File.AppendAllLines从.NET Framework 4.0开始存在.如果使用的是.NET Framework 3.5,则有AppenAllText方法,您可以这样编写代码:
System.IO.File.AppendAllLines exists from .NET framework 4.0. If you are using .NET framework 3.5, there is AppenAllText method, and you can write your code like this:
File.WriteAllText("important.txt", Convert.ToString(c));
File.AppendAllText("important.txt", string.Join(Environment.NewLine, (from r in rec
select r.name + " " + r.num1 + " " + r.num2 + " " + r.mult + " " + r.rel).ToArray()));
这篇关于附加在C#的文本文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!