Csharp Not able to read excel using oledb - c#

I was trying to read an Excel file from an .aspx page using Visual Studio localhost. I kept the Excel in the root folder, but when trying to read it, it shows the following exception:
The Microsoft Office Access database engine cannot open or write to
the file ''. It is already opened exclusively by another user, or you
need permission to view and write its data.
My oledb code
string connString = ConfigurationManager.ConnectionStrings["xlsx"].ConnectionString;
OleDbConnection oledbConn = new OleDbConnection(connString);
try
{
// Open connection
oledbConn.Open();
// Create OleDbCommand object and select data from worksheet Sheet1
OleDbCommand cmd = new OleDbCommand("SELECT * FROM [Sheet1$]", oledbConn);
// Create new OleDbDataAdapter
OleDbDataAdapter oleda = new OleDbDataAdapter();
oleda.SelectCommand = cmd;
// Create a DataSet which will hold the data extracted from the worksheet.
DataSet ds = new DataSet();
// Fill the DataSet from the data extracted from the worksheet.
oleda.Fill(ds, "Employees");
// Bind the data to the GridView
GridView1.DataSource = ds.Tables[0].DefaultView;
GridView1.DataBind();
}
catch(Exception ex)
{
throw ex;
}
finally
{
// Close connection
oledbConn.Close();
}
connection string
<connectionStrings>
<add name="xls" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=ExcelToParse.xls;Extended Properties=Excel 8.0"/>
<add name="xlsx" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=ExcelToParse.xlsx;Extended Properties=Excel 12.0"/>
</connectionStrings>
Can somebody point what I am doing wrong here?

First run this command in command prompt to kill all open Excel processes.
taskkill /f /im excel.exe
You need to dispose the connection object. Then change your code in your finally block to-
finally
{
// Close connection
oledbConn.Close();
oledbConn.Dispose();
System.Runtime.InteropServices.Marshal.ReleaseComObject(oledbConn);
}
Please let me know if it works.

Related

Read a dbase IV file C#

I am developing an application to recover data from a DBF file.
I did research on the Internet that sent me to this link : enter link description here
I applied this code but nothing helps it doesn't work :/
string constr = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Test\users.dbf;Extended Properties=dBASE IV;User ID=;Password=MyPassword;";
using (OleDbConnection con = new OleDbConnection(constr))
{
var sql = "select * from users.dbf";
OleDbCommand cmd = new OleDbCommand(sql, con);
con.Open();
DataSet ds = new DataSet(); ;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(ds);
}
I pass this code in a Try and Catch and it returns me this error: Unable to start your application. The workgroup information file is missing or opened exclusively by another user.
the error is caused when trying to open the connection. However the file is neither opened nor used by anyone else.
thank you in advance ;)
Try to remove the file name in the connection string. According to the documentation, The "Data Source" property should only contain the path.
string constr = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Test;Extended Properties=dBASE IV;User ID=;Password=MyPassword;";

The Microsoft Jet database engine cannot open the file It is already opened exclusively by another user, or you need permission to view its data

Firstly please don't mark it as duplicate I know it's been asked multiple times here but none of the links helped me.
I am trying to access database which is located on shared drive, also both the mdb file and the folder in which it is stored have full access to everyone. I have hosted my application on two different machines.
Below is the code to connect to access DB
OleDbDataAdapter dataAdapter = null;
DataTable dtAttendance = new DataTable();
try
{
string conStr = System.Configuration.ConfigurationManager.ConnectionStrings["AccessDBPath"].ToString();
using (OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Mode= Share Deny None;Data Source= " + conStr))
{
conn.Open();
OleDbCommand cmd = new OleDbCommand(#"Select EmployeeId AS UserId,AttendanceDate , format(Int(Duration/60),'0') AS Duration,format(Duration Mod 60,'0') AS Remain FROM AttendanceLogs
where EmployeeId =" + userid.ToString() + " and Year(AttendanceDate)="+year+" and Month(AttendanceDate)="+month+" order by AttendanceDate desc", conn);
dataAdapter = new OleDbDataAdapter();
dataAdapter.SelectCommand = cmd;
dataAdapter.Fill(dtAttendance);
conn.Close();
}
}
catch(Exception ee)
{}
Only first time when I tested it, it worked properly and thereafter it started throwing above error.

An attempt to attach an auto-named database for file \bin\Debug\aspnetdb.mdf failed

I am developing a Class Library in C# and in this Class Library I am trying to access database through ADO.NET code, But I'm getting this error. I don't know what is the reason behind it. So please tell me how can I solve it.
System.Data.SqlClient.SqlException: An attempt to attach an auto-named database for file C:\Users\vivek.nuna\Documents\VisualStudio2005\Projects\SubsystemSyncService\TestClient\bin\Debug\aspnetdb.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.
This is the connection string I am using.
<connectionStrings>
<add name="RegistrationConnString"
connectionString="Server=192.168.101.145\SQLEXPRESS;Database=***_HubDB;User Id=sa;Password={C8273EFD-LB2F-4E65-8702-14B61PI08A9}"
providerName="System.Data.SqlClient" />
</connectionStrings>
Note: I can't see a file aspnetdb.mdf in the Debug folder.
This is the code, how I am using ado.net code.
private DataSet GetAddressFieldsAccordingtoAddressId(string strAddressId)
{
try
{
strConnString = ConfigurationManager.ConnectionStrings["RegistrationConnString"].ToString();
SqlConnection connection = new SqlConnection(strConnString);
SqlCommand command = new SqlCommand();
command.CommandType = System.Data.CommandType.StoredProcedure;
command.CommandText = "[dbo].[PL_spPLUIGetAddressFieldsAccordingtoAddressId]";
command.Parameters.Add("#lAddressID", System.Data.SqlDbType.Int).Value = Convert.ToInt32(strAddressId);
command.Connection = connection;
DataSet dsPwd = new DataSet();
SqlDataAdapter dAdapter = new SqlDataAdapter(command);
dAdapter.Fill(dsPwd);
command.Dispose();
dAdapter.Dispose();
return dsPwd;
}
catch (Exception ex)
{
return null;
}
}
I have added reference of this class Library in a C# form.
C# form is calling this method of class library.
If you want a standalone database for your application, you should have a look at
SQL Server Compact : http://www.microsoft.com/sqlserver/2008/en/us/compact.aspx
SQLite : http://sqlite.phxsoftware.com/
For connectionstrings see http://www.connectionstrings.com/access-2003/.
SqlCeConnection sqlConnection1 = new SqlCeConnection();
sqlConnection1.ConnectionString = "Data Source = C:\\Users\\Administrator\\My Documents\\BMS_Data.sdf;Persist Security Info=False";

Get data from the excel file using c# asp.net

I am trying to load data using following code.
string path = System.IO.Path.GetFullPath(uploadExcelFile.PostedFile.FileName);
string connString = "provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\Rizwan shahid\\Desktop\\DataUpload\\Req.xls;Extended Properties=Excel 12.0;";
OleDbConnection oledbConn = new OleDbConnection(connString);
try
{
oledbConn.Open();
OleDbCommand cmd = new OleDbCommand("SELECT * FROM [Sheet1$]", oledbConn);
OleDbDataAdapter oleda = new OleDbDataAdapter();
oleda.SelectCommand = cmd;
DataSet ds = new DataSet();
oleda.Fill(ds, "Table");
return ds.Tables[0];
}
catch
{
return null;
}
finally
{
oledbConn.Close();
}
It was working on 32Bit operating system but when run this code on 64Bit OS it gives the following error
The Microsoft Access database engine could not find the object 'Sheet1$'. Make sure the object exists and that you spell its name and the path name correctly. If 'Sheet1$' is not a local object, check your network connection or contact the server administrator.
I am running VS in Administrator mode and found many solution like replace Sheet1 with file name or place file in C drive but still getting the same error.
you can download latest version here of Jet
http://www.microsoft.com/en-us/download/search.aspx?q=jet
This works (I start out with a 'dummy' path and then apply the real runtime path):
OleStringBuilder =
new OleDbConnectionStringBuilder(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\MyExcel.xls;Extended Properties='Excel 8.0;HDR=Yes;IMEX=1';");
OleStringBuilder.DataSource = MapPath(#"~\App_Data\MyExcelWorksheet.xls");

C# Open DBF file

I'm having a problem opening a DBF file - I need to open it, read everything and process it. I tried several solutions (ODBC/OLEDB), several connection string, but nothing worked so far.
The problem is, when I execute the SQL command to get everything from the file, nothing gets returned - no rows. What's even more odd, the content of the DBF file being opened get deleted.
See the code I have:
public override bool OpenFile(string fileName, string subFileName = "")
{
OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Path.GetDirectoryName(fileName) + ";Extended Properties=dBASE IV;User ID=;Password=;");
try
{
if (con.State == ConnectionState.Closed) { con.Open(); }
OleDbDataAdapter da = new OleDbDataAdapter("select * from " + Path.GetFileName(fileName), con);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
int i = ds.Tables[0].Rows.Count;
return true;
}
catch
{
return false;
}
}
I debugged the code and watched the file being opend in Windows Explorer. When it reached this line:
da.Fill(ds);
the size of the file dropped to only a few Bytes (from hundreds of kB).
My next thought was to make the DBF file read only. That however cause an "unexpected exception from an external driver".
So my question is - what the heck? I'm sure the file is not corrupt, it is a direct export from some DB. (No, I do not have access to that DB). I can also open that file in MS Office no problem.
I cannot share the DBF file - it contains confidential data.
Two things... just because its a .DBF file extension might night mean its a Dbase IV file. It might actually be that of Visual Foxpro. That said, I would look into downloading and installing the Visual Foxpro OleDB driver from Microsoft download. Next, the OleDbConnection is pointing to the path that has the actual tables (you already have that).
The query itself, shouldn't care about the extension, so I would change your call to get just then name via "Path.GetFileNameWithoutExtension"
It might be a combination of the two.
Connection string for VFP provider
"Provider=VFPOLEDB.1;Data Source=" + FullPathToDatabase
This is not the exact answer but it will help you to find the issue.
Try to give an inline connection string and select query to make sure problem is not with building those. Catch the exception and check the details of it.
OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\folder;Extended Properties=dBASE IV;User ID=;Password=;"); // give your path directly
try
{
con.Open();
OleDbDataAdapter da = new OleDbDataAdapter("select * from tblCustomers.DBF", con); // update this query with your table name
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
int i = ds.Tables[0].Rows.Count;
return true;
}
catch(Exception e)
{
var error = e.ToString();
// check error details
return false;
}

Categories

Resources