少し前に、かなり大きなテキスト ファイルを区切って読み取るプログラムを作成しました。プログラムは動作しますが、問題は基本的にコンピューターがフリーズし、完了するまでに時間がかかることです。平均して、各テキスト ファイルには約 10,000 ~ 15,000 行あり、各行は SQL テーブルの新しい行を表します。
私のプログラムの仕組みは、最初にすべての行を読み取り (ここで区切りが行われる場所です)、それらを配列に格納します。その後、各配列要素を調べて SQL テーブルに挿入します。これはすべて一度に行われ、プログラムがコンピューターをフリーズさせる原因となっている大量のメモリを消費していると思われます。
ファイルを読み取るための私のコードは次のとおりです。
private void readFile()
{
//String that will hold each line read from the file
String line;
//Instantiate new stream reader
System.IO.StreamReader file = new System.IO.StreamReader(txtFilePath.Text);
try
{
while (!file.EndOfStream)
{
line = file.ReadLine();
if (!string.IsNullOrWhiteSpace(line))
{
if (this.meetsCondition(line))
{
badLines++;
continue;
} // end if
else
{
collection.readIn(line);
counter++;
} // end else
} // end if
} // end while
file.Close();
} // end try
catch (Exception exceptionError)
{
//Placeholder
}
挿入するコード:
for (int i = 0; i < counter; i++)
{
//Iterates through the collection array starting at first index and going through until the end
//and inserting each element into our SQL Table
//if (!idS.Contains(collection.getIdItems(i)))
//{
da.InsertCommand.Parameters["@Id"].Value = collection.getIdItems(i);
da.InsertCommand.Parameters["@Date"].Value = collection.getDateItems(i);
da.InsertCommand.Parameters["@Time"].Value = collection.getTimeItems(i);
da.InsertCommand.Parameters["@Question"].Value = collection.getQuestionItems(i);
da.InsertCommand.Parameters["@Details"].Value = collection.getDetailsItems(i);
da.InsertCommand.Parameters["@Answer"].Value = collection.getAnswerItems(i);
da.InsertCommand.Parameters["@Notes"].Value = collection.getNotesItems(i);
da.InsertCommand.Parameters["@EnteredBy"].Value = collection.getEnteredByItems(i);
da.InsertCommand.Parameters["@WhereReceived"].Value = collection.getWhereItems(i);
da.InsertCommand.Parameters["@QuestionType"].Value = collection.getQuestionTypeItems(i);
da.InsertCommand.Parameters["@AnswerMethod"].Value = collection.getAnswerMethodItems(i);
da.InsertCommand.Parameters["@TransactionDuration"].Value = collection.getTransactionItems(i);
da.InsertCommand.ExecuteNonQuery();
//}
//Updates the progress bar using the i in addition to 1
_worker.ReportProgress(i + 1);
} // end for