我正在使用 C# 中的 CsvHelper 库将股票的 OHLC 数据实时写入 csv 文件中。一切工作正常,但当我打开文件查看数据时,它给我一个异常,指出“进程无法访问文件‘FileLocation’”。有没有一种方法可以在不出现此异常的情况下编写它,并且在每个新条目之后我可以使用独立于该条目运行的其他程序来读取相同的内容?
您可以尝试将文件设置为只读。在写入文件之前关闭只读,然后在写入后立即将文件设置回只读。
void Main()
{
var records = new List<Foo>
{
new Foo { Id = 1, Name = "one" },
};
var config = new CsvConfiguration(CultureInfo.InvariantCulture)
{
HasHeaderRecord = false
};
string filePath = @"c:\Temp\myfile.csv";
FileInfo fInfo = new FileInfo(filePath);
fInfo.IsReadOnly = false;
using (var writer = new StreamWriter(filePath, true))
using (var csv = new CsvWriter(writer, config))
{
csv.WriteRecords(records);
}
fInfo.IsReadOnly = true;
}
public class Foo
{
public int Id { get; set; }
public string Name { get; set; }
}
如果您阅读该文件,请确保打开该文件时将
FileAccess
设置为 FileAccess.Read
并将 FileShare
设置为 FileShare.ReadWrite
。
void Main()
{
string filePath = @"c:\Temp\myfile.csv";
var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
using (var reader = new StreamReader(fs))
using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
{
csv.Read();
csv.ReadHeader();
while (csv.Read())
{
var record = csv.GetRecord<Foo>();
}
}
}
public class Foo
{
public int Id { get; set; }
public string Name { get; set; }
}