The Microsoft Jet database engine could not find the object - c#

Here users browse to the Excel file from there system and then data is uploaded to sql database table.
I get this Error in Following Code : The Microsoft Jet database engine could not find the object 'C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\Student Registration1.xls'. Make sure the object exists and that you spell its name and the path name correctly.
I have no idea why it is asking for this Path ? C:\Program
Files\Microsoft Visual Studio 9.0\Common7\IDE\
protected void import_xls_Click(object sender, EventArgs e)
{
try
{
if (xmlupload.HasFile)
{
string path = xmlupload.PostedFile.FileName;
string excelConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties='Excel 8.0;HDR=YES;IMEX=1'";
OleDbConnection excelConnection = new OleDbConnection(excelConnectionString);
excelConnection.Open();
OleDbCommand cmd = new OleDbCommand("select * from [Sheet2$]", excelConnection);
OleDbDataReader dReader = cmd.ExecuteReader();
SqlBulkCopy sqlBulk = new SqlBulkCopy(SqlConnectionstring.mainConnectionString, SqlBulkCopyOptions.KeepIdentity);
sqlBulk.DestinationTableName = "dbo.studentA";
sqlBulk.ColumnMappings.Add("UserName", "UserName");
sqlBulk.ColumnMappings.Add("Password", "Password");
sqlBulk.ColumnMappings.Add("Name", "Name");
sqlBulk.ColumnMappings.Add("Standard", "Standard");
sqlBulk.ColumnMappings.Add("Division", "Division");
sqlBulk.ColumnMappings.Add("SchoolName", "SchoolName");
sqlBulk.ColumnMappings.Add("Language", "Language");
sqlBulk.ColumnMappings.Add("ExamStatus", "ExamStatus");
sqlBulk.ColumnMappings.Add("Result", "Result");
sqlBulk.WriteToServer(dReader);
lblmsg.Visible = true;
lblmsg.Text = "Your data uploaded successfully";
excelConnection.Close();
}
}
catch (Exception ex)
{
lblmsg.Visible = true;
lblmsg.Text = ex.Message.ToString();
}
SqlConnectionstring.cs :
public class SqlConnectionstring
{
public SqlConnectionstring()
{
//
// TODO: Add constructor logic here
//
}
public static readonly string mainConnectionString = ConfigurationManager.ConnectionStrings["constring"].ToString();
}

I will try to save the file in a working directory and then try to open from there.
If the fileName has no path then the connection could find the file only if it is in the
current directory (Usually where your program start)
string savePath = #"c:\temp\uploads";
if (xmlupload.HasFile)
{
string fileName = xmlupload.FileName;
savePath = Path.Combine(savePath, fileName);
xmlupload.SaveAs(savePath);
string excelConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
savePath + ";Extended Properties='Excel 8.0;HDR=YES;IMEX=1'";
....
On a web server, to avoid permission problems, it is better to keep the file in a subfolder of the root folder of your site.
In this case the folder could be fully qualified using the HttpServerUtility.MapMath method.

Related

Visual studio app.config file database path for installed apps

I am using local database in my app and when I generate installation file (By Installer Package), after installing program it gives database path errors.
Eample
an attempt to attach an auto-named database for file....
//OR
The given path format is not supported
I've tried to edit database path in app.config file but it failed every time, By default my code line is like this:
<add name="SampleDatabaseWalkthrough.Properties.Settings.SampleDatabaseConnectionString"
connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\SampleDatabase.mdf;Integrated Security=True"
providerName="System.Data.SqlClient" />
And my app installing in C:\Program Files (86)\App_Folder\Setup Please note that future users might install it in custom path so I need a way to get dynamic path of installed app.
My question is How can I get app installed path to replace with this part AttachDbFilename=|DataDirectory|\SampleDatabase.mdf?
You could try to use AppDomain.CurrentDomain.SetData method to change your mdf file path.
Since, I don't know how do you published the winform project.
I recommend that you use Clickonce to publish it.
First, please include your mdf file in your project.
Second, you could try the following code to change the installed path after you published it.
private void Form1_Load(object sender, EventArgs e)
{
if(System.Deployment.Application.ApplicationDeployment.IsNetworkDeployed)
{
string path = ApplicationDeployment.CurrentDeployment.DataDirectory; //Get installed path
AppDomain.CurrentDomain.SetData("DataDirectory", path);//set the DataDirectory
}
}
Finally, based on my test, I can get the information from the mdf file after I publised it and installed it in another computer.
In production mode |DataDirectory| refers to 'bin' directory, not 'app_data'. If you placed the .mdf file in the app_data directory, you can change it like this:
|DataDirectory|\SampleDatabase.mdf to |DataDirectory|\app_data\SampleDatabase.mdf
<add name="SampleDatabaseWalkthrough.Properties.Settings.SampleDatabaseConnectionString"
connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\app_data\SampleDatabase.mdf;Integrated Security=True"
providerName="System.Data.SqlClient" />
Update1:
I'm sending some code. I just want to give you an idea. You can change it for your situation.
private void Form1_Load(object sender, EventArgs e)
{
if (!IsExist())
{
CreateDatabase();
CreateTables();
}
}
// Create the Database
private void CreateDatabase()
{
string basePath = Environment.CurrentDirectory;
string mdfFile = "TestDatabase.mdf";
string ldfFile = "TestDatabase_Log.mdf";
string mdfFullPath = System.IO.Path.Combine(basePath, "Data", mdfFile);
string ldfFullPath = System.IO.Path.Combine(basePath, "Data", ldfFile);
SqlConnection myConn = new SqlConnection("Server=.;Data Source=(LocalDB)\\MSSQLLocalDB;Integrated security=SSPI;database=master");
string str = "CREATE DATABASE TestDatabase ON PRIMARY " +
"(NAME = TestDatabase, " +
$"FILENAME = '{mdfFullPath}', " +
"SIZE = 2MB, MAXSIZE = 10MB, FILEGROWTH = 10%)" +
"LOG ON (NAME = MyDatabase_Log, " +
$"FILENAME = '{ldfFullPath}', " +
"SIZE = 1MB, " +
"MAXSIZE = 5MB, " +
"FILEGROWTH = 10%)";
SqlCommand myCommand = new SqlCommand(str, myConn);
try
{
myConn.Open();
myCommand.ExecuteNonQuery();
MessageBox.Show("DataBase is Created Successfully", "MyProgram", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (System.Exception ex)
{
MessageBox.Show(ex.ToString(), "MyProgram", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
finally
{
if (myConn.State == ConnectionState.Open)
{
myConn.Close();
}
}
}
// Create the tables and other stuff that you want
private void CreateTables()
{
string conStr = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Data\TestDatabase.mdf;Integrated Security=True;Connect Timeout=30";
SqlConnection myConn = new SqlConnection(conStr);
string str = #"CREATE TABLE [dbo].[TestTable]
(
[Id] INT NOT NULL PRIMARY KEY,
[Test] NVARCHAR(50) NULL
)";
SqlCommand myCommand = new SqlCommand(str, myConn);
try
{
myConn.Open();
myCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "MyProgram", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
finally
{
if (myConn.State == ConnectionState.Open)
{
myConn.Close();
}
}
}
// Check if there is the database
private bool IsExist()
{
string basePath = Environment.CurrentDirectory;
string mdfFile = "TestDatabase.mdf";
string mdfFullPath = System.IO.Path.Combine(basePath, "Data", mdfFile);
return System.IO.File.Exists(mdfFullPath);
}

Importation of Master data with standard validation

I had excel file, button (import), openfiledialog and gridview at VB.Net 2013.
My task is to make a button that will extract all data from excel file to datagridview
openFileDialog1.InitialDirectory = "C:\\Users\\ProgrammerPC1\\Desktop\\DLAV FILES";
openFileDialog1.Title = "Import Master Data";
openFileDialog1.FileName = "";
openFileDialog1.Filter = "Excel Files|*.xls;*.xlsx;*.xlsm";
try {
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
string name = "Sheet1";
string constr = #"provider=Microsoft.Jet.OLEDB.4.0;Data Source='" + openFileDialog1.FileName + "'; Extended Properties=Excel 8.0; HDR=Yes; IMEX=1;";
System.Data.OleDb.OleDbConnection con = new System.Data.OleDb.OleDbConnection(constr);
System.Data.OleDb.OleDbCommand oconn = new System.Data.OleDb.OleDbCommand("SELECT * FROM [" + name + "$]", con);
con.Open();
System.Data.OleDb.OleDbDataAdapter adapter = new System.Data.OleDb.OleDbDataAdapter(oconn);
DataTable data = new DataTable();
adapter.Fill(data);
dataGridView1.DataSource = data;
}
else
{
MessageBox.Show("Operation Cancelled");
}
}catch (Exception err)
{
MessageBox.Show(err.Message);
}
My Error is
external table is not in the expected format
I found that you're using same connection string provider (MS Jet OLEDB 4.0 Provider) for both XLS (for Excel 97-2003) and XLSX (for Excel 2007 & above) files, hence causing external table is not in the expected format error when trying to read XLSX/XLSM files.
You need to use 2 separate connection string and switch them based from file extension stored in OpenFileDialog with Path.GetExtension() method as in given example below:
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
string extension = Path.GetExtension(openFileDialog1.FileName); // get file extension
string name = "Sheet1"
using (System.Data.OleDb.OleDbConnection con = new System.Data.OleDb.OleDbConnection())
{
switch (extension)
{
case ".xls": // Excel 97-2003 files
// Excel 97-2003 connection string
string xlsconstr = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source='" + openFileDialog1.FileName + "'; Extended Properties=Excel 8.0; HDR=Yes; IMEX=1;";
con.ConnectionString = xlsconstr;
break;
case ".xlsx": // Excel 2007 files
case ".xlsm":
// Excel 2007+ connection string, see in https://www.connectionstrings.com/ace-oledb-12-0/
string xlsxconstr = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + openFileDialog1.FileName + "'; Extended Properties=Excel 12.0; HDR=Yes; IMEX=1;";
con.ConnectionString = xlsxconstr;
break;
}
using (System.Data.OleDb.OleDbCommand oconn = new System.Data.OleDb.OleDbCommand("SELECT * FROM [" + name + "$]", con))
{
con.Open();
System.Data.OleDb.OleDbDataAdapter adapter = new System.Data.OleDb.OleDbDataAdapter(oconn);
DataTable data = new DataTable();
adapter.Fill(data);
dataGridView1.DataSource = data;
}
}
}
else
{
MessageBox.Show("Operation Cancelled");
}

Unable to connect MS Access DB in Server

I am trying to connect the MS Access Database from the server and finding no luck.
I see the below image("Insert Operation Error") message while trying to save the information.
Can anyone please help? What went wrong in the below code?
Insert Operation Error
protected void btnsave_Click(object sender, EventArgs e)
{
string constring = "PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA SOURCE=" + Server.MapPath("DB\\Contact.DB");
string SqlString = "Insert Into BUREAUXDETUDES (mail1,mail2,tel1,tel2) Values (#mail1,#mail2,#tel1,#tel2)";
OleDbConnection con = new OleDbConnection(constring);
try
{
OleDbCommand cmd = new OleDbCommand(SqlString, con);
con.Open();
cmd.Parameters.AddWithValue("#mail1", txtemail1.Text);
cmd.Parameters.AddWithValue("#mail2", txtemail2.Text);
cmd.Parameters.AddWithValue("#tel1", txttel1.Text);
cmd.Parameters.AddWithValue("#tel2", txttel2.Text);
cmd.ExecuteNonQuery();
lblmessage.Text = "Your Information Saved Successfully";
}
catch (Exception emsg)
{
lblmessage.Text = emsg.Message;
}
finally
{
con.Close();
}
}
The Error is telling you that the location of your .db file is incorrect.
You can change the path to the file in this line.
string constring = "PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA SOURCE=" + Server.MapPath("DB\\Contact.DB");
You need to install Microsoft Excel engine first.
You can download it from the link bellow
https://www.microsoft.com/en-us/download/details.aspx?id=13255

The Microsoft Jet database engine cannot open the file c#

Hi I am having some issues reading a CSV file with the Jet Database engine. I get this message:
The Microsoft Jet database engine cannot open the file 'C:\Users\mikec\Desktop\'. It is already opened exclusively by another user, or you need permission to view its data.
I have permission to access this folder and file. I have also tried putting in my Visual Studio project and still get the same error. This is my code
string path = #"C:\Users\mikec\Desktop\Book1.csv";
string full = Path.GetFullPath(path);
string file = Path.GetFileName(full);
string dir = Path.GetDirectoryName(full);
//create the "database" connection string
string connString = "Provider=Microsoft.Jet.OLEDB.4.0;"
+ "Data Source=\"" + dir + "\\\";"
+ "Extended Properties=\"Excel 8.0;HDR=Yes;FMT=Delimited\"";
//create the database query
string query = "SELECT * FROM " + file;
//create a DataTable to hold the query results
DataTable dTable = new DataTable();
OleDbConnection con = new OleDbConnection(connString);
//create an OleDbDataAdapter to execute the query
OleDbDataAdapter dAdapter = new OleDbDataAdapter(query, con);
try
{
//fill the DataTable
dAdapter.Fill(dTable);
}
catch (InvalidOperationException e)
{
}
I'm confused to why this is happening I've looked around the Internet and cannot find a solution.
It would be great if anyone out there could point me in the right direction.
Thanks.

Read DBF file: System.Data.OleDb.OleDbException

I am trying to open a DBF in C# file and upload it to a MySQL database. Right now I am just trying to open the DBF file, but I am getting the following error:
A first chance exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll
Error: Failed to retrieve the required data from the DataBase.
Unrecognized database format 'C:\Users\Path\..\..\..\SOMEFILE.DBF'.
My code is as follows.
private void button2_Click(object sender, EventArgs e)
{
DirectoryInfo dir = new DirectoryInfo(Regex.Replace(textBox1.Text, #"\\", #"\\"));
foreach (FileInfo file in dir.GetFiles())
{
MessageBox.Show(file.Name);
string strAccessConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + dir + file.Name;
string strAccessSelect = "SELECT * FROM "+file.Name.Substring(0,file.Name.Length-4);
DataSet myDataSet = new DataSet();
OleDbConnection myAccessConn = null;
try
{
myAccessConn = new OleDbConnection(strAccessConn);
}
catch (Exception ex)
{
Console.WriteLine("Error: Failed to create a database connection. \n{0}", ex.Message);
return;
}
try
{
OleDbCommand myAccessCommand = new OleDbCommand(strAccessSelect, myAccessConn);
OleDbDataAdapter myDataAdapter = new OleDbDataAdapter(myAccessCommand);
myAccessConn.Open();
myDataAdapter.Fill(myDataSet);
}
catch (Exception ex)
{
Console.WriteLine("Error: Failed to retrieve the required data from the DataBase.\n{0}", ex.Message);
return;
}
finally
{
myAccessConn.Close();
}
}
}
I only get the first MessageBox with the file name and then it throws the error.
Your connection string should identify that the OleDB data source is a DBASE type:
string strAccessConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + dir + ";Extended Properties=dBase III";
Also note that when connecting to DBase via OleDB, you do not specify the DBF file, but rather the folder which contains it. The individual files are tables.
Use datasource without file name, only path.
string strAccessConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + dir;

Categories