写入/编辑CSV文件(不重写整个文件!) [英] Write/Edit CSV-file (not rewrite the whole file!)

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

问题描述

我可能要替换直接在CSV文件上运行的客户端的某些功能,该CSV文件用作系统的配置文件。

I'm in a situation to replace some functionalities from a client that operates directly on a CSV file, which used as a config file for a system.

搜索中可用的大多数案例都涉及从CSV读取为其他格式。

Most of the cases available on search is about reading from CSV to other formats.

Other将整个CSV放入内存,附加专用行和更改,然后将其写回到新文件(或覆盖现有文件)。

Other takes the whole CSV into memory, attaching the dedicated rows and changes, then write them back to a new file (or overwrite existing).

我想更聪明地完成此任务,并寻求建议和编码思路。

我们可以假设每次只有一个用户可以访问该文件。

该文件使用File.ReadLines().NET 4读取。

I would like to do this task smarter and ask for advices and code ideas.
We can presume that just one user per time, should have access to the file.
The file reads with File.ReadLines() .NET 4.

我的示例项目的一部分,

A part from my sample project,

   var lines = from l in File.ReadLines("/Linq2Csv/data.csv")
               where l.Split(',')[0].StartsWith("Jonas") //Just test 'n pick 1 line
               select new
               {
                 Name = l.Split(',')[0],
                 ...


推荐答案

CSV文件只是一个连续的文本文件。

A CSV file is just a sequential text file.

如果要修改您拥有的内容将整个文件读取到内存中,然后在其中进行修改并再次写出。

If you want to modify the contents you have to read the entire file into memory, modify it there and write it out again.

假设文件的情况更一般包含以下内容:

Assume a more general case of a file that contains the following:


ABCDEFGHIJKLMNOPQRSTUV

ABCDEFGHIJKLMNOPQRSTUV

如果要从中间删除 IJLKM,则必须阅读文件的其余部分(NOP ...),以便可以将其改组以达到(... FGH)。

If you want to remove "IJLKM" from the middle you have to read the remainder of the file (NOP...) so you can shuffle it up to meet (...FGH).

如果要在其中插入 0123456789在 M和 N之间,您需要阅读NZ,否则新字符将仅覆盖 NOPQRSTUVW。

If you want to insert "0123456789" in between "M" and "N" you need to read N-Z otherwise the new characters will just overwrite "NOPQRSTUVW".

这篇关于写入/编辑CSV文件(不重写整个文件!)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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