views:

29

answers:

1

I am receiving the following error in my code (c#, .Net 3.5, VS2008) when I try to connect to an Excel sheet and fill a OleDbDataAdapter with the results of a query. First the error:

Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

And here is the code, which is honestly pretty simple:

var excelFileName = @"c:\Metadata_Tool.xlsm";
var connectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0; Data Source={0}; Extended Properties=Excel 12.0;HDR=YES;", excelFileName);

var adapter = new OleDbDataAdapter("Select * FROM [Video Tagging XML]", connectionString);
var ds = new DataSet();

adapter.Fill(ds, "VTX");

DataTable data = ds.Tables["VTX"];

foreach (DataRow myRow in data.Rows)
{
    foreach (DataColumn myColumn in data.Columns)
    {
        Console.Write("\t{0}", myRow[myColumn]);
    }
    Console.WriteLine();
}

Console.ReadLine();

I get the error on the line adapter.Fill(ds,"VTX");. I did find a microsoft forum post saying to turn on JIT optimization in VS2008 from the Tools/Options/Debug/General menu, but this did not seem to help. Any help would be greatly appreciated thanks!

+2  A: 

The error appears to be generated from within the ACE provider. My guess is that it's because your connection string is wrong.

Instead of:

var excelFileName = "c:/Metadata_Tool.xlsm";

You should have:

var excelFileName = @"c:\Metadata_Tool.xlsm";

Note the backslash instead of forward slash. You need the @ character at the front to prevent the backslash from being escaped. You also don't need the string.Format at all - you aren't formatting anything on this line.

Aaronaught
I gave this a try, and although you are right about the formatting, unfortunately that did not solve the problem. I am getting the same error.
Tim C
@Tim C: Are you sure the file is there? With the correct permissions applied? Have you tried opening it in Excel? Have you tried this same code on a fresh, blank Excel file that you created by hand with only a couple of rows?
Aaronaught
It does seem to be with the Excel file! The file was in the correct location and had all of the permissions, but when I changed to another file, it worked fine. Something is corrupt about this one. Thank you!
Tim C