遵循此操作后topic https://stackoverflow.com/questions/13100139/update-one-column-in-csv-file-c-sharp我能够创造
新行,但我的问题是怎么做
我将新行保存或写入文件吗?
我尝试了“StreamWriter”,但它只写入新的
创建的线。
请问有什么建议吗?
到目前为止,这是我的代码:
string path = @"C:/CSV.txt";
string[] lines = File.ReadAllLines(path);
var splitlines = lines.Select(l => l.Split(','));
foreach (var line in splitlines)
{
if(line[1].Contains("34"))
{
line[1] = "100";
var newline = string.Join(",", line);
StreamWriter sr = new StreamWriter(path);
sr.WriteLine(newline);
sr.Close();
}
}
这是您使用的解决方案StreamReader
class:
String path = @"C:\CSV.txt";
List<String> lines = new List<String>();
if (File.Exists(path));
{
using (StreamReader reader = new StreamReader(path))
{
String line;
while ((line = reader.ReadLine()) != null)
{
if (line.Contains(","))
{
String[] split = line.Split(',');
if (split[1].Contains("34"))
{
split[1] = "100";
line = String.Join(",", split);
}
}
lines.Add(line);
}
}
using (StreamWriter writer = new StreamWriter(path, false))
{
foreach (String line in lines)
writer.WriteLine(line);
}
}
如果您想覆盖该文件,请使用this http://msdn.microsoft.com/en-us/library/36b035cb.aspxStreamWriter 构造函数append = false
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)