-2

我正在 .csv 文件中生成报告。

我正在使用下面的代码通过按钮单击事件上的代码打开一个 .csv 文件。

    StreamWriter sw = new StreamWriter(AbsolutePathAndFileName);

        //write header line
        int iColCount = TheDataTable.Columns.Count;
        for (int i = 0; i < iColCount; i++)
        {
            sw.Write(TheDataTable.Columns[i]);
            if (i < iColCount - 1)
            {
                sw.Write(separator);
            }
        }
        sw.Write(sw.NewLine);

        //write rows
        foreach (DataRow dr in TheDataTable.Rows)
        {
            for (int i = 0; i < iColCount; i++)
            {
                if (!Convert.IsDBNull(dr[i]))
                {
                    string data = dr[i].ToString();
                    data = data.Replace("\"", "\\\"").Replace(",", " ");
                    sw.Write(quote + data + quote);
                }
                if (i < iColCount - 1)
                {
                    sw.Write(separator);
                }
            }
            sw.Write(sw.NewLine);
        }
        sw.Close();



 MsgBox db = new MsgBox("Please select below option.", "Message", MessageBoxIcon.Information);
                db.SetButtons("Open Master File", "Save Master File", strBasePath + "\\master.csv");
                db.ShowDialog(this);

这段代码对我来说很好。

现在我的文件处于打开模式。如果正在过滤另一个标准以再次打开报告(.csv 文件),那么它会向我抛出错误,该文件被另一个进程使用。

我该如何解决该错误?

4

1 回答 1

0

ChrisWIs there a way to check if a file is in use 给出了很好的回答?

您可以使用以下示例代码检查您的文件是否正在使用中:

protected virtual bool IsFileLocked(FileInfo file)
{
    FileStream stream = null;

    try
    {
        stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
    }
    catch (IOException)
    {
        //the file is unavailable because it is:
        //still being written to
        //or being processed by another thread
        //or does not exist (has already been processed)
        return true;
    }
    finally
    {
        if (stream != null)
            stream.Close();
    }

    //file is not locked
    return false;
}

希望这可以帮助。

于 2012-08-17T06:53:33.627 回答