2 回答

TA貢獻(xiàn)1804條經(jīng)驗(yàn) 獲得超8個(gè)贊
我建議使用File類(lèi)而不是Streams 和Readers。Linq在查詢(xún)數(shù)據(jù)的時(shí)候非常方便:
var modifiedData = File
.ReadLines(file.ToString())
.Select(line => line.Split(','))
.Select(items => {
//TODO: put relevant logic here: given items we should return csv line
items[10] = "my value";
return string.Join(",", items);
})
.ToList(); // <- we have to store modified data in memory
File.WriteAllLines(file.ToString(), modifiedData);
另一種可能性(例如,當(dāng)初始文件太長(zhǎng)而無(wú)法容納內(nèi)存時(shí))是將修改后的數(shù)據(jù)保存到一個(gè)臨時(shí)文件中,然后Move:
var modifiedData = File
.ReadLines(file.ToString())
.Select(line => line.Split(','))
.Select(items => {
//TODO: put relevant logic here: given items we should return csv line
items[10] = "my value";
return string.Join(",", items);
});
string tempFile = Path.Combine(Path.GetTempPath(), $"{Guid.NewGuid()}.tmp");
File.WriteAllLines(tempFile, modifiedData);
File.Delete(file.ToString());
File.Move(tempFile, file.ToString());

TA貢獻(xiàn)1840條經(jīng)驗(yàn) 獲得超5個(gè)贊
一次讀取整個(gè)文件會(huì)占用大量?jī)?nèi)存。更不用說(shuō)創(chuàng)建它的平行副本了。使用流可以修復(fù)它。嘗試這個(gè):
void Modify()
{
using (var fs = new FileStream(file, FileMode.Open, FileAccess.ReadWrite))
{
string line;
long position;
while ((line = fs.ReadLine(out position)) != null)
{
var tmp = line.Split(',');
tmp[1] = "00"; // new value
var newLine = string.Join(",", tmp);
fs.WriteLine(position, newLine);
}
}
}
擴(kuò)展名:
static class FileStreamExtensions
{
private static readonly char[] newLine = Environment.NewLine.ToCharArray();
private static readonly int length = Environment.NewLine.Length;
private static readonly char eof = '\uFFFF';
public static string ReadLine(this FileStream fs, out long position)
{
position = fs.Position;
var chars = new List<char>();
char c;
while ((c = (char)fs.ReadByte()) != eof && (chars.Count < length || !chars.Skip(chars.Count - 2).SequenceEqual(newLine)))
{
chars.Add(c);
}
fs.Position--;
if (chars.Count == 0)
return null;
return new string(chars.ToArray());
}
public static void WriteLine(this FileStream fs, long position, string line)
{
var bytes = line.ToCharArray().Concat(newLine).Select(c => (byte)c).ToArray();
fs.Position = position;
fs.Write(bytes, 0, bytes.Length);
}
}
缺點(diǎn)是您必須保持值的長(zhǎng)度相同。例如999和__9的長(zhǎng)度都是 3。解決這個(gè)問(wèn)題會(huì)使事情變得更加復(fù)雜,所以我會(huì)這樣處理。
- 2 回答
- 0 關(guān)注
- 247 瀏覽
添加回答
舉報(bào)