Hac*_*ese 15
过程将是这样的:
StreamWriter临时文件.StreamReader目标文件.关于步骤2和3.1的注意事项:如果您对文件的结构有信心并且它很简单,那么您可以按照所描述的方式开箱即用(我稍后会包含一个示例).但是,CSV文件中的某些因素可能需要引起注意(例如,识别何时在列值中使用分隔符).您可以自己解决这个问题,或尝试现有的解决方案.
仅使用StreamReader和的基本示例StreamWriter:
var sourcePath = @"C:\data.csv";
var delimiter = ",";
var firstLineContainsHeaders = true;
var tempPath = Path.GetTempFileName();
var lineNumber = 0;
var splitExpression = new Regex(@"(" + delimiter + @")(?=(?:[^""]|""[^""]*"")*$)");
using (var writer = new StreamWriter(tempPath))
using (var reader = new StreamReader(sourcePath))
{
string line = null;
string[] headers = null;
if (firstLineContainsHeaders)
{
line = reader.ReadLine();
lineNumber++;
if (string.IsNullOrEmpty(line)) return; // file is empty;
headers = splitExpression.Split(line).Where(s => s != delimiter).ToArray();
writer.WriteLine(line); // write the original header to the temp file.
}
while ((line = reader.ReadLine()) != null)
{
lineNumber++;
var columns = splitExpression.Split(line).Where(s => s != delimiter).ToArray();
// if there are no headers, do a simple sanity check to make sure you always have the same number of columns in a line
if (headers == null) headers = new string[columns.Length];
if (columns.Length != headers.Length) throw new InvalidOperationException(string.Format("Line {0} is missing one or more columns.", lineNumber));
// TODO: search and replace in columns
// example: replace 'v' in the first column with '\/': if (columns[0].Contains("v")) columns[0] = columns[0].Replace("v", @"\/");
writer.WriteLine(string.Join(delimiter, columns));
}
}
File.Delete(sourcePath);
File.Move(tempPath, sourcePath);
Run Code Online (Sandbox Code Playgroud)
小智 6
内存映射文件是.NET Framework 4中的一项新功能,可用于编辑大型文件.在这里阅读http://msdn.microsoft.com/en-us/library/dd997372.aspx 或google内存映射文件