I am extracting data from .txt files and writing needed data to Excel. My problem is that my code is very very slow and at one point even slower (+35k txt files). How should I rethink this problem?
Microsoft.Office.Interop.Excel.Application excelapp = new Microsoft.Office.Interop.Excel.Application();
excelapp.Visible = true;
_Workbook workbook = (_Workbook)(excelapp.Workbooks.Open(textBox2.Text));
_Worksheet worksheet = (_Worksheet)workbook.ActiveSheet;
DateTime dt = DateTime.Now;
foreach (string fileName in Directory.GetFiles(textBox1.Text, "*.txt"))
{
int row = 1, EmptyRow = 0;
while (Convert.ToString(worksheet.Range["A" + row].Value) != null)
{
row++;
EmptyRow = row;
}
string lines1 = GetLine(fileName, 10);
File.WriteAllText(@"D:/text.txt", lines1);
string[] ParsedLines = File.ReadAllLines(@"D:/text.txt");
string comp = ParsedLines[0];
string compare = comp.Substring(30, comp.Length - 30);
if (compare == "Failed")
{
string[] lines = File.ReadAllLines(fileName);
string serial = lines[3];
string SN = serial.Substring(30, serial.Length - 30);
worksheet.Range["A" + EmptyRow].Value2 = SN;
string data = lines[4];
string DT = data.Substring(30, data.Length - 30);
worksheet.Range["B" + EmptyRow].Value2 = DT;
string time = lines[5];
string TM = time.Substring(30, time.Length - 30);
worksheet.Range["C" + EmptyRow].Value2 = TM;
string operat = lines[6];
string OP = operat.Substring(30, operat.Length - 30);
worksheet.Range["D" + EmptyRow].Value2 = OP;
string result = lines[9];
string PF = result.Substring(30, result.Length - 30);
worksheet.Range["E" + EmptyRow].Value2 = PF;
foreach (string line in lines)
{
if (line.Contains("FixtureCoverResistance:"))
{
string FCResistance = line;
string FCR = FCResistance.Substring(31, FCResistance.Length - 31);
worksheet.Range["F" + EmptyRow].Value2 = FCR;
break;
}
}
foreach (string line in lines)
{
if (line.Contains("FwProgrammingCheck:"))
{
string FwProgrammingCheck = line;
string FwP = FwProgrammingCheck.Substring(31, FwProgrammingCheck.Length - 31);
worksheet.Range["G" + EmptyRow].Value2 = FwP;
break;
}
}
foreach (string line in lines)
{
if (line.Contains("Checksum ="))
{
string Checksum = line;
string da = Checksum.Substring(11, Checksum.Length - 11);
worksheet.Range["H" + EmptyRow].Value2 = da;
}
}
foreach (string line in lines)
{
if (line.Contains("FwEepromCheck:"))
{
string FwEepromCheck = line;
string FwE = FwEepromCheck.Substring(31, FwEepromCheck.Length - 31);
worksheet.Range["I" + EmptyRow].Value2 = FwE;
break;
}
}
foreach (string line in lines)
{
if (line.Contains("FixtureCoverResistanceAfterProg:"))
{
string FixtureCoverResistanceAfterProg = line;
string FCAP = FixtureCoverResistanceAfterProg.Substring(33, FixtureCoverResistanceAfterProg.Length - 33);
worksheet.Range["K" + EmptyRow].Value2 = FCAP;
break;
}
}
}
else
{
}
}
foreach
iterating over the same content. Have you considered iterating only once? \$\endgroup\$