I am normally using Java and only use C# for reading an old MS Access 95 Database so I am new to this. I have a C# script that opens an OleDBConnection to the access db and reads several data from it:
using System;
using System.Data.OleDb;
namespace ReadMsAccessDB
{
class Program
{
static void Main(string[] args)
{
const string connectionString = "Provider = Microsoft.Jet.OLEDB.4.0; Data Source = C:/workspace-csharp/ReadMsAccessDB/ReadMsAccessDB/File/remote.mdb; Persist Security Info = True";
using (var con = new OleDbConnection(connectionString))
{
con.OpenAsync();
var cmd = con.CreateCommand();
cmd.CommandText = "select * from summary_0199_550";
cmd.Connection = con;
using (var dataReader = cmd.ExecuteReader())
{
while (dataReader.Read())
{
var output = "ScanDateTime: " + dataReader.GetValue(3) + "\n"
+ "RCP_Name: " + dataReader.GetValue(13) + "\n"
+ "Slot: " + dataReader.GetValue(14) + "\n"
+ "DFCT_Tot: " + dataReader.GetValue(19) + "\n"
+ "Area_Count: " + dataReader.GetValue(22) + "\n"
+ "Part1: " + dataReader.GetValue(23) + "\n"
+ "Part2: " + dataReader.GetValue(24) + "\n"
+ "Part3: " + dataReader.GetValue(25) + "\n"
+ "Part4: " + dataReader.GetValue(26) + "\n"
+ "Part5: " + dataReader.GetValue(27) + "\n"
+ "Part6: " + dataReader.GetValue(28) + "\n"
+ "Part7: " + dataReader.GetValue(29) + "\n"
+ "Part8: " + dataReader.GetValue(30) + "\n"
+ "HazeRegion: " + dataReader.GetValue(33) + "\n"
+ "HazeAverage: " + dataReader.GetValue(34) + "\n"
+ "HazePeak: " + dataReader.GetValue(35) + "\n\n";
Console.WriteLine(output);
}
}
}
Console.ReadLine();
}
}
}
The project is a console app and when I hit Run in Visual Studio while having the configuration mode on Debugging
it works perfectly fine. But when I try to run it without Debugging Mode or publishing it and try to run the .exe file I get an connection Error like this:
Unhandled exception. System.InvalidOperationException: ExecuteReader requires an open and available Connection. The connection's current state is closed.
at System.Data.OleDb.OleDbConnection.CheckStateOpen(String method)
at System.Data.OleDb.OleDbCommand.ValidateConnection(String method)
at System.Data.OleDb.OleDbCommand.ValidateConnectionAndTransaction(String method)
at System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior behavior, String method)
at System.Data.OleDb.OleDbCommand.ExecuteReader(CommandBehavior behavior)
at ReadMsAccessDB.Program.Main(String[] args) in C:\workspace-csharp\ReadMsAccessDB\ReadMsAccessDB\Program.cs:line 18
I dont understand why it says that the connection state is closed because I am opening the connection with con.OpenAsync();
in the using section?