如何使用c#组合两个.csv文件? [英] How can I combine two .csv files using c#?

查看:233
本文介绍了如何使用c#组合两个.csv文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要说我是新手,这将是一个低估。

我的痛苦点?

我有一个文件,我们称之为1.csv。

我有另一个文件,让我们打电话它是2.csv。

我想要做的是将2.csv附加到1.csv而不覆盖2.csv的内容。

我不需要担心格式或列标题,因为它们是相同的。



1.csv是新数据,2.csv会是一个主文件。

例如,如果1.csv有10行,2.csv有10行,当文件合并时,新文件名为2.csv 会有20行。



我希望这是有道理的。我试图尽可能地自动化以使我的日子更轻松,编程是一个令人沮丧的爆炸,但是当它工作时,什么是RUSH!



感谢您的帮助!

尼克

To say I'm new at this would be understating.
My point of pain?
I have a file, lets call it "1.csv".
I have another file, let's call it "2.csv".
what I am trying to do is append "2.csv" with "1.csv" without overwriting the contents of 2.csv.
I don't need to worry about format or column headers as they are the same.

"1.csv" is new data and "2.csv" would be a "master" file.
For instance, if "1.csv" has 10 rows and "2.csv" has 10 rows, when the files are combined the new file named "2.csv" would have 20 rows.

I hope this makes sense. I am trying to automate as much as possible to make my day easier and programming is a frustrating blast, but when it works, what a RUSH!

Thanks for any help!
Nick

推荐答案

最简单的方法可能是

The simplest way is probably
using System.IO;
...
File.AppendAllText(originalFilePath, File.ReadAllText(appendFilePath));







阅读你的评论,我想知道它不适用于你。上面将一个文本文件附加到现有文件。如果CSV文件不是太复杂(即没有多行字段,在新行上正确终止),那么不应该有任何格式问题(即,当你报告时,所有格式问题都在一列(?))。我唯一能想到的就是字符编码。这就是为什么看到你的文件(或至少是它的一小部分和混淆部分)很好的原因。
[/编辑]



干杯

Andi




Reading your comments, I wonder what went wrong that it does not work with you. The above appends one text file to an existing one. If the CSV file is not too elaborate (i.e. no multi-line fields, terminates properly on a new-line), then there should not be any format issues (i.e. that all is now in one column(?) as you report). The only thing I could imagine is the character encoding. That's why it was good to see your files (or at least a small and obfuscated portion of it).
[/EDIT]

Cheers
Andi


你好!



试试这样的......



Hello!

Try something like this...

StreamReader rdr = new StreamReader("<pathtoyourmasterfile>");
string master = rdr.ReadToEnd();
rdr.Close();

rdr = new StreamReader("<pathtoyournewdatafile>");
string newdata = rdr.ReadToEnd();
rdr.Close();
rdr.Dispose();

//The New Data .csv file will have headers. Need to remove those.
newdata = newdata.Substring(newdata.IndexOf('\n') + 1);

StreamWriter wtr = new StreamWriter("<pathtoyourmasterfile>");
wtr.Write(master + "\r\n" /*That \r\n may or may not be necessary*/ + newdata);
wtr.Close();
wtr.Dispose();





我希望你能理解它是如何工作的!如果您需要澄清,请告诉我: - )



I hope you understand how it works! If you want clarification let me know :-)


这篇关于如何使用c#组合两个.csv文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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