0

からCSVファイルを書いていますDataGridView。プロセス中 (タスクがファイルに書き込んでいる間) にファイルを開くと、次の理由でエラーが発生します。

The process cannot access the file 'xyz\filename.csv' because it is being used by another process.

Flush()両方の書き込み後にメソッドをfile手動で呼び出してみましswOutたが、それでもエラーが発生します。

FileMode.Appendファイルの作成後にn行を追加するため、使用する必要があります。FileShare列挙のさまざまなオプションをそれぞれ試しましたが、何も機能していません。

どこが間違っていますか?

私のコード:

using (FileStream file = new FileStream(output_file, FileMode.Append, FileAccess.Write, FileShare.Read))
{
    StreamWriter swOut = new StreamWriter(file);
    swOut.AutoFlush = true;
    if (table.Rows.Count == 2)
    {
        for (int i = 0; i <= table.Columns.Count - 1; i++)
        {
            if (i > 0)
            {
                swOut.Write(",");
            }
            swOut.Write(table.Columns[i].HeaderText);
        }
        swOut.WriteLine();
    }
    swOut.Write(category.Replace(",", " ") + "," + name.Replace(",", " ") + "," + address.Replace(",", " ") + "," + locality.Replace(",", " ") + "," + cap.Replace(",", " ") + "," + tel.Replace(",", " ") + "," + fax.Replace(",", " ") + "," + www.Replace(",", " ") + "," + email_results.Replace(",", " ") + "," + business_url.Replace(",", " ") + "," + map_query.Replace(",", " "));
    swOut.WriteLine();
    file.Close();
    if (stop == true) output_file = "";
}
4

3 に答える 3

1

なぜfile.Close();ですか?

そのはずswOut.Close();

編集済み:

または、このように

'using (FileStream file = new FileStream(output_file, FileMode.Append, FileAccess.Write, FileShare.Read))
using (StreamWriter swOut = new File.AppendText(output_file))
{
    'StreamWriter swOut = new StreamWriter(file);
    swOut.AutoFlush = true;
    if (table.Rows.Count == 2)
    {
        for (int i = 0; i <= table.Columns.Count - 1; i++)
        {
            if (i > 0)
            {
                swOut.Write(",");
            }
            swOut.Write(table.Columns[i].HeaderText);
        }
        swOut.WriteLine();
    }
    swOut.Write(category.Replace(",", " ") + "," + name.Replace(",", " ") + "," + address.Replace(",", " ") + "," + locality.Replace(",", " ") + "," + cap.Replace(",", " ") + "," + tel.Replace(",", " ") + "," + fax.Replace(",", " ") + "," + www.Replace(",", " ") + "," + email_results.Replace(",", " ") + "," + business_url.Replace(",", " ") + "," + map_query.Replace(",", " "));
    swOut.WriteLine();
    swOut.Close();
    if (stop == true) output_file = "";
}
于 2013-06-17T02:38:22.343 に答える