我有一個要求複製文件,解析它的內容刪除換行符,並沿着管道拆分內容,然後將結果字符串[]關閉存儲在數據庫中。我的文件每個文件最多可以有65000條有效記錄,因此性能至關重要。在C#中讀取文件的優化#
下面是我目前有。問題是非常緩慢(處理65000行3小時)。我會很感激任何幫助改善優化這件作品,所以我的跑步可以更快。
public void ReadFileLinesIntoRows()
{
try
{
using (var reader = new TextFieldParser(FileName))
{
reader.HasFieldsEnclosedInQuotes = false;
reader.TextFieldType = FieldType.Delimited;
reader.SetDelimiters("|");
String[] currentRow;
while (!reader.EndOfData)
{
try
{
currentRow = reader.ReadFields();
int rowcount = currentRow.Count();
//if it is less than what you need, pad it.
if (rowcount < 190)
{
Array.Resize<string>(ref currentRow, 190);
rows.Add(currentRow);
}
else
{
rows.Add(currentRow);
}
}
catch (MalformedLineException mex)
{
unreadlines.Add(reader.ErrorLine);//continue afterwards
}
}
this.TotalRowCount = rows.Count();
}
}
catch (Exception ex)
{
throw ex;
}
}
public void cleanfilecontent(String tempfilename, Boolean? HeaderIncluded)
{
try
{
//remove the empty lines in the file
using (var sr = new StreamReader(tempfilename))
{
// Write new file
using (var sw = new StreamWriter(CleanedCopy))
{
using (var smove = new StreamWriter(duptempfileremove))
{
string line;
Boolean skippedheader = false;
while ((line = sr.ReadLine()) != null)
{
// Look for text to remove
if (line.Contains("----------------------------------"))
{
smove.Write(line);
}
else if (HeaderIncluded.HasValue && HeaderIncluded.Value==true && ! skippedheader)
{
smove.Write(line);
skippedheader = true;
}
else if(skippedheader)
{
// Keep lines that does not match
sw.WriteLine(line);
}
}
smove.Flush();
}
sw.Flush();
}
sr.Close();
}
}
catch (Exception ex)
{
throw ex;
}
}
那麼問題是什麼? – zerkms
你的'TextFieldParser'看起來像什麼? –
TextFieldParser lib在Microsoft.VisualBasic.FileIO – Kobojunkie