在读取 CSV 文件时替换值并保存文件 (C#)

我正在阅读 csv 文件:


string line;


StreamReader sr = new StreamReader(file.ToString());


while ((line = sr.ReadLine()) != null)

{

    string col1 = line.Split(',')[10]; //old value

    col1 = "my value"; //new value

}


sr.Close();

sr.Dispose();

我想用新值替换旧值。


然后我需要保存更改后的文件。


我怎样才能做到这一点?


叮当猫咪
浏览 189回答 2
2回答

胡说叔叔

我建议使用File类而不是Streams 和Readers。Linq在查询数据的时候非常方便:var modifiedData = File&nbsp; .ReadLines(file.ToString())&nbsp; .Select(line => line.Split(','))&nbsp;&nbsp; .Select(items => {&nbsp; &nbsp; &nbsp;//TODO: put relevant logic here: given items we should return csv line&nbsp; &nbsp; &nbsp;items[10] = "my value";&nbsp; &nbsp; &nbsp;return string.Join(",", items);&nbsp; &nbsp;})&nbsp; .ToList(); // <- we have to store modified data in memoryFile.WriteAllLines(file.ToString(), modifiedData);另一种可能性(例如,当初始文件太长而无法容纳内存时)是将修改后的数据保存到一个临时文件中,然后Move:&nbsp;var modifiedData = File&nbsp; .ReadLines(file.ToString())&nbsp; .Select(line => line.Split(','))&nbsp;&nbsp; .Select(items => {&nbsp; &nbsp; &nbsp;//TODO: put relevant logic here: given items we should return csv line&nbsp; &nbsp; &nbsp;items[10] = "my value";&nbsp; &nbsp; &nbsp;return string.Join(",", items);&nbsp; &nbsp;});&nbsp;string tempFile = Path.Combine(Path.GetTempPath(), $"{Guid.NewGuid()}.tmp");&nbsp;File.WriteAllLines(tempFile, modifiedData);&nbsp;File.Delete(file.ToString());&nbsp;File.Move(tempFile, file.ToString());

慕斯709654

一次读取整个文件会占用大量内存。更不用说创建它的平行副本了。使用流可以修复它。尝试这个:void Modify(){&nbsp; &nbsp; using (var fs = new FileStream(file, FileMode.Open, FileAccess.ReadWrite))&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; string line;&nbsp; &nbsp; &nbsp; &nbsp; long position;&nbsp; &nbsp; &nbsp; &nbsp; while ((line = fs.ReadLine(out position)) != null)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var tmp = line.Split(',');&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; tmp[1] = "00"; // new value&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var newLine = string.Join(",", tmp);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fs.WriteLine(position, newLine);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}扩展名:static class FileStreamExtensions{&nbsp; &nbsp; private static readonly char[] newLine = Environment.NewLine.ToCharArray();&nbsp; &nbsp; private static readonly int length = Environment.NewLine.Length;&nbsp; &nbsp; private static readonly char eof = '\uFFFF';&nbsp; &nbsp; public static string ReadLine(this FileStream fs, out long position)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; position = fs.Position;&nbsp; &nbsp; &nbsp; &nbsp; var chars = new List<char>();&nbsp; &nbsp; &nbsp; &nbsp; char c;&nbsp; &nbsp; &nbsp; &nbsp; while ((c = (char)fs.ReadByte()) != eof && (chars.Count < length || !chars.Skip(chars.Count - 2).SequenceEqual(newLine)))&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; chars.Add(c);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; fs.Position--;&nbsp; &nbsp; &nbsp; &nbsp; if (chars.Count == 0)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return null;&nbsp; &nbsp; &nbsp; &nbsp; return new string(chars.ToArray());&nbsp; &nbsp; }&nbsp; &nbsp; public static void WriteLine(this FileStream fs, long position, string line)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; var bytes = line.ToCharArray().Concat(newLine).Select(c => (byte)c).ToArray();&nbsp; &nbsp; &nbsp; &nbsp; fs.Position = position;&nbsp; &nbsp; &nbsp; &nbsp; fs.Write(bytes, 0, bytes.Length);&nbsp; &nbsp; }}缺点是您必须保持值的长度相同。例如999和__9的长度都是 3。解决这个问题会使事情变得更加复杂,所以我会这样处理。
打开App,查看更多内容
随时随地看视频慕课网APP