The Microsoft Jet database engine cannot open the file c# - 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.

Related

Problems trying to read dbf file in C#

I am trying to read a dbf file in C#, but first I had the error
System.InvalidOperationException: 'The provider' Microsoft.ACE.OLEDB.12.0 'is not registered on the local machine.'
Then I installed Microsoft Access Database Engine 2010 Redistributable and now I have the error
The Microsoft Access database engine cannot open or write to the file 'C:\Users\Emmanuel\Desktop\Proyectos\program'. It is already opened exclusively by another user, or you need permission to view and write its data.'
This is the code I'm using:
var constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;";
var sql = "select * from " + file;
var ds = new DataTable();
using (var con = new OleDbConnection(constr))
{
con.Open();
using (var cmd = new OleDbCommand(sql, con))
{
using (var da = new OleDbDataAdapter(cmd))
{
da.Fill(ds);
}
}
}
Also I've tried this but I have this error
System.Data.Odbc.OdbcException: 'ERROR [HY000] [Microsoft] [ODBC dBase Driver] The external table is not in the expected format.'
string fullPath = path + file;
string sConn = "Driver={Microsoft dBASE Driver (*.dbf)};SourceType=DBF;SourceDB=" + path + ";Exclusive=No; NULL=NO;DELETED=NO;BACKGROUNDFETCH=NO;";
using (OdbcConnection dbConn = new OdbcConnection(sConn))
{
dbConn.Open();
OdbcCommand oCmd = dbConn.CreateCommand();
oCmd.CommandText = "SELECT * FROM " + fullPath;
/* Load data to table */
DataTable dt1 = new DataTable();
dt1.Load(oCmd.ExecuteReader());
dbConn.Close();
}

Read Excel File Data From OleDbConnection

I'm currently facing a problem whereby I don't know how to fix it.
I upload my precompiled project into IIS. Here is my purpose of this page:
User upload a excel file into a folder in the server. ex #"~/PlanQuantityFile/". It did upload successfully.
Problems faced:
It stops when my scripts trying to open the excel file (for extract data purpose) without showing any errors. At line 881 as shown in the image.
Here is few area I had seek for but it still couldn't solve my problem.
Possible Solution:
connection open but never close, so run out of connection. (but I did close it and the scripts stop running before the close statement)
32 bit program calling 64 bit office. (I had limited knowledge on hardware field, don't know what should I do to troubleshoot here)
permission problem. Need to set the permission of ASP.NET account. (I still finding object names for ASP.NET account)
Thanks for anyone who trying to help. Your advice is invaluable.
OleDbConnection oledbConn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + SaveLocation + ";Extended Properties='Excel 12.0;HDR=YES;IMEX=1;';");
OleDbConnection connExcel = oledbConn;
OleDbCommand cmdExcel = new OleDbCommand();
OleDbDataAdapter oda = new OleDbDataAdapter();
DataTable dt = new DataTable();
cmdExcel.Connection = connExcel;
//Get the name of Sheet
try
{
connExcel.Open();// It stops here without showing errors.
}
catch (Exception ex)
{
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + ex.Message + "');", true);
}
The following code returns a datatable for selected filelocation source. Remember to rename the sheetname to "Sheet1".
Use Namespace: using System.Data.OleDb;
Function::::
public DataTable GetExcelinDatatable(string filelocation)
{
DataTable dt = new DataTable();
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filelocation + ";Extended Properties=\"Excel 8.0;HDR=YES;\"";
OleDbConnection con = new System.Data.OleDb.OleDbConnection(connectionString);
con.Open();
OleDbDataAdapter da = new System.Data.OleDb.OleDbDataAdapter("select * from [SHEET1$]", con);
da.Fill(dt);
con.Close();
return dt;
}
you can use mentioned function to read the Excel file you have to just pass the path of excel file
private List<DataTable> readExcel(string strXLS)
{
//DataTable dtExcel = getExcelSheetTable();
List<DataTable> SheetsData = new List<DataTable>();
DataTable dtExcel = new DataTable();
DataTable SocialMediaExcel = new DataTable();
string connStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + strXLS + ";Extended Properties=Excel 12.0;";
try
{
OleDbDataAdapter adpt = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", connStr);
adpt.Fill(dtExcel);
SheetsData.Add(dtExcel);
}
catch (Exception ex)
{
throw ex;
}
return SheetsData;
}

The Microsoft Access database engine could not find the object 'Sheet1$

I am copying the template excel file saved in the server folder in to the same folder with different name. to insert the value..I am able to copy the file but when I try to insert the values it shows sheet!$ could not found. I have given correct sheet name..Only one sheet is added in the spread sheet named as sheet1.still it shows error .My code is given below.Nay idea about this error .I googled but asked me to check the folder and sheet name..it is correct only..please help me
string xxx = "~/temp/" + "Tempfile" + dunsno + DateTime.Today.ToString("dd.MM.yyyy") + ".xlsx";
DirectoryInfo directoryInfo = new DirectoryInfo(Server.MapPath("~/temp/"));
var fileList = directoryInfo.GetFiles();
string newFileName = Server.MapPath("~/temp/" + "Tempfile" + dunsno + DateTime.Today.ToString("dd.MM.yyyy") + ".xlsx");
foreach (FileInfo fleInfo in fileList
{
fleInfo.CopyTo(newFileName, true);
}
string connStr = String.Format(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=xxx;Extended Properties=""Excel 12.0 Xml;HDR=YES""");
OleDbConnection MyConnection;
OleDbCommand MyCommand = new OleDbCommand();
MyConnection = new OleDbConnection(#connStr);
MyConnection.Open();
MyCommand.Connection = MyConnection;
string sql = "Insert into [Sheet1$] (id,name) values('3','c')";
MyCommand.CommandText = sql;
MyCommand.ExecuteNonQuery();
MyConnection.Close();
Replace:
string connStr = String.Format(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=xxx;Extended Properties=""Excel 12.0 Xml;HDR=YES""");
with
string connStr = String.Format(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0 Xml;HDR=YES""", newFileName);
In case if you are still getting error as follows "The Microsoft Access database engine could not find the object..." followed by the sheet name from where you are trying to read data then try [sheetname$].

OleDBException when reading an open excel file

I have an excel file and an oledb connection to it. When reading data while file is opened in windows, it throws the following error (at Adapter.Fill method).
However, the code runs fine when file is not opened manually.
private System.Data.DataSet GetExcelData()
{
// Create new DataSet to hold information from the worksheet.
System.Data.DataSet objDataset1 = new System.Data.DataSet();
DataTable dt = new DataTable();
try
{
string path = ConfigurationManager.AppSettings["ExcelFilePath"];
//string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;";
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1;\"";
OleDbConnection objConn = new OleDbConnection(connectionString);
objConn.Open();
//String strConString = "SELECT * FROM [Data Version5.2$A2:ZZ] where [Status] = 'aa'";//Status
String strConString = "SELECT * FROM [Data Version5.2$A2:ZZ] where [Status] IS NULL OR [Status]='SubReport'";//Status SubReport
OleDbCommand objCmdSelect = new OleDbCommand(strConString, objConn);
OleDbDataAdapter objAdapter1 = new OleDbDataAdapter();
// Pass the Select command to the adapter.
objAdapter1.SelectCommand = objCmdSelect;
// Fill the DataSet with the information from the work sheet.
objAdapter1.Fill(objDataset1, "ExcelData");
objConn.Close();
}
catch (Exception ex)
{
throw ex;
}
return objDataset1;
}
The error message is
Assuming you don't need to write to the file, try adjusting your connection string to include the read only mode (Mode=Read). I have that in all of mine (where I don't need to write to the file) and I've never had a problem reading from workbooks that are already open:
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
path + ";Mode=Read;Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1;\"";
I also don't tend to read Excel files as XML, so the Extended Properties for my connection strings are Excel 12.0;HDR=YES;IMEX=1;

Importing CSV into web application

I have a process that allows the user to download a spreadsheet, make some changes, and then upload those changes.
The upload method looks like -
public DataTable ImportXLS(String SourceFilePath) {
string ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + SourceFilePath + ";" +
"Extended Properties=Excel 8.0;";
using (OleDbConnection cn = new OleDbConnection(ConnectionString)) {
cn.Open();
DataTable dbSchema = cn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dbSchema == null || dbSchema.Rows.Count < 1) {
throw new Exception("Error: Could not determine the name of the first worksheet.");
}
string WorkSheetName = dbSchema.Rows[0]["TABLE_NAME"].ToString();
OleDbDataAdapter da = new OleDbDataAdapter("SELECT * FROM [" + WorkSheetName + "]", cn);
DataTable dt = new DataTable(WorkSheetName);
da.Fill(dt);
return dt;
}
}
When I call the method locally, it works because I can see my local drives.
When deployed to the web server, and called like -
ExportImport _ei = new ExportImport();
DataTable dt = null;
dt = _ei.ImportXLS("C:\Users\mike\Desktop\mike.xls");
I get an error that "C:\Users\mike\Desktop\mike.xls" is not a valid path, obviously because it doesn't exist on the web server.
Has anyone had any experience with trying to upload files over the web and how do you resolve the file location issue?
You need to add a FileUpload control to your Asp.Net page. On a button click you need to the save the file on the server by calling:
FileUpload1.SaveAs("C:\\Uploads\\" + FileUpload1.FileName);
Afterwards you can call you method to process the file
ExportImport _ei = new ExportImport();
DataTable dt = null;
dt = _ei.ImportXLS("C:\\Uploads\\" + FileUpload1.FileName);
So the idea is to upload the file first to the server before processing it.
A link on using the FileUpload control (.Net 2.0)
http://msdn.microsoft.com/en-us/library/aa479405.aspx
You can use Server.MapPath to get the virtual location of your app. Have a look at this article.

Categories