How to open multiple Microsoft Access (mdb) files in C#? - c#

Referring to this question, I figured out how open and connect to a single mdb file.
At the moment I am doing:
String accessConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;
Data Source=C:\MyMDB\MyMDBFile.mdb;
Persist Security Info = False; ";
using (OleDbConnection accessConnection = new OleDbConnection(accessConnectionString))
{
ReadContent();
}
But I want to open multiple files from the directory, basically I want to:
String[] mdbFiles = Directory.GetFiles(#"C:\MyMDB\", "*.mdb");
And use this in the accessConnectionString
I know it should be something like,
foreach (var filePath in mdbFiles)
{
accessConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;"
+ "Data Source=" + filePath + " Persist Security Info = False; ";
}
But is this the only way to access multiple mdb files?

Related

Run a sql script in c# (.asp net)

I just want the directory to open to "project_name\Scripts(sub_folder)\merge.sql"
I can't get rid of 'C:' and I cant get the actually data file to appear.
I received an"System.io.directorynotfoundexcpetion".
Here's my code:
private void MergeQuery()
{
//might need to change C: drive directory
//string derefQuery = #"\.\mergeSQL.sql";
using (SqlConnection mer = new SqlConnection(#"Data Source = address_name; Initial Catalog = catalog_name; Integrated Security=SSPI"))
{
{
mer.Open();
string path = Path.GetDirectoryName("\\project_name\\Scripts\\mergeSQL.sql ");
string mergeScript = System.IO.File.ReadAllText(path);
System.Collections.Generic.IEnumerable<string> commandStrings = Regex.Split(mergeScript, #"^\s*GO\s*$", RegexOptions.Multiline | RegexOptions.IgnoreCase);
foreach (string commandString in commandStrings)
{
if (commandString.Trim() != "")
{
using (var command = new SqlCommand(commandString, mer))
{
command.ExecuteNonQuery();
}
Label2.Text = "Query merged";
}
}
}
}
first, there is an error in line
string path = Path.GetDirectoryName("\\project_name\\Scripts\\mergeSQL.sql ");
In that line you're getting directory path from file path, so path variable becomes \\project_name\\Scripts\\ or something similar. On next line you're trying to read file from that path variable, not from file.
What you need is to get path relative to web site root and then read file, like this
string path = HostingEnvironment.MapPath("~/Scripts/mergeSQL.sql ");
string mergeScript = System.IO.File.ReadAllText(path);
this way asp.net will get correct path from your website root's subfolder.

How to edit linked app.config and save changes in all exe config

I am working on winform c# application, having single app.config linked in all the projects.
I'm trying to create one project, which can edit and update connection string in app.config. But currently I'm only able to change particular project's exe.config.
How I can change all exe.config in particular solution?
Thanks in advance.
Loop through all exe.config file in application folder and using XmlDocument; I'm changing connection string for all and saving it again.
string curAssembly = Assembly.GetExecutingAssembly().Location;
string FolderPath = Path.GetDirectoryName(curAssembly);
string[] files = Directory.GetFiles(FolderPath).Where(x => x.EndsWith(".config")).ToArray();
foreach (string item in files)
{
XmlDocument XmlDoc = new XmlDocument();
XmlDoc.Load(item);
foreach (XmlElement xElement in XmlDoc.DocumentElement)
{
if (xElement.Name == "connectionStrings")
{
foreach (XmlElement xChild in xElement)
{
if (xChild.Attributes.Count > 1 && xChild.Attributes[0].Value == ConfigSectionName)
{
xChild.Attributes[1].Value = "Data Source=" + cmbDatasource.Text + ";Initial Catalog=" + cmbDatabaseName.Text + ";UID=" + txtUserName.Text + ";password=" + txtPassword.Text + ";Integrated Security = false;";
Connectionstring = xChild.Attributes[1].Value;
}
}
}
}
XmlDoc.Save(item);
}

Why won't my code upload a file to the specified folder on the web server when using the fileupload control?

Good afternoon. I have an asp.net web forms application using c#. I am having some difficulty getting my code to work properly. The data is uploaded successfully to the sql server database, but the file isn't saved to the specified "Data" folder. any help would be greatly appreciated?
The ID of the fileupload control is "fu_doc_upld". I don't get any errors when using the form, the files just aren't saving to the "Data" folder (or any other folder). Here is the code behind that I'm using:
protected void btn_frm_new_doc_save_close_Click(object sender, EventArgs e)
{
int i = 0;
string filename = fu_doc_upld.FileName;
if (fu_doc_upld.HasFile)
{
while (System.IO.File.Exists(Server.MapPath("~/Data/") + filename))
{
i++;
filename = fu_doc_upld.FileName + " (" + i.ToString() + ")";
fu_doc_upld.PostedFile.SaveAs(Server.MapPath("~/Data/") + filename);
}
}
hdn_filename_txt.Value = (Server.MapPath("~/Data/") + filename);
hdn_doc_uplod_dt_txt.Value = DateTime.Now.ToString();
SqlConnection idrf_cnxn = new SqlConnection("Data Source=WDBSVCPRD01\\SVCDB;Initial Catalog=idrf;Integrated Security=True");
{
SqlCommand new_doc_cmd = new SqlCommand("Insert Into tbl_doc(doc_title, doc_type_list, doc_org_list, doc_dept_list, doc_desc, prior_contract_cd, legal_comp_contract_id, doc_upld_dt, doc_path, vendor_id_fk) Values(LTRIM(RTRIM(#doc_title)), LTRIM(RTRIM(#doc_type_list)), LTRIM(RTRIM(#doc_org_list)), LTRIM(RTRIM(#doc_dept_list)), LTRIM(RTRIM(#doc_desc)), LTRIM(RTRIM(#prior_contract_cd)), LTRIM(RTRIM(#legal_comp_contract_id)), LTRIM(RTRIM(#doc_upld_dt)), LTRIM(RTRIM(#doc_path)), LTRIM(RTRIM(#vendor_id_fk)))", idrf_cnxn);
new_doc_cmd.Parameters.AddWithValue("#doc_title", doc_title_txt.Text);
new_doc_cmd.Parameters.AddWithValue("#doc_type_list", doc_type_ddl.Text);
new_doc_cmd.Parameters.AddWithValue("#doc_org_list", doc_org_ddl.Text);
new_doc_cmd.Parameters.AddWithValue("#doc_dept_list", doc_dept_ddl.Text);
new_doc_cmd.Parameters.AddWithValue("#doc_desc", doc_desc_txt.Text);
new_doc_cmd.Parameters.AddWithValue("#prior_contract_cd", prior_contract_cd_txt.Text);
new_doc_cmd.Parameters.AddWithValue("#legal_comp_contract_id", lgl_comp_cont_id_txt.Text);
new_doc_cmd.Parameters.AddWithValue("#doc_upld_dt", hdn_doc_uplod_dt_txt.Value);
new_doc_cmd.Parameters.AddWithValue("#doc_path", hdn_filename_txt.Value);
new_doc_cmd.Parameters.AddWithValue("#vendor_id_fk", hdn_vendor_id_txt.Value);
idrf_cnxn.Open();
new_doc_cmd.ExecuteNonQuery();
idrf_cnxn.Close();
if (IsPostBack)
{
Response.Redirect("~/Default.aspx");
}
}
}
Any help would be greatly appreciated.
Thanks,
J
You only call SaveAs() when the file exists. You could've found this by placing a breakpoint and stepping through your code.
Move the save out of the loop:
string filename = fu_doc_upld.FileName;
while (System.IO.File.Exists(Server.MapPath("~/Data/") + filename))
{
i++;
filename = fu_doc_upld.FileName + " (" + i.ToString() + ")";
}
fu_doc_upld.PostedFile.SaveAs(Server.MapPath("~/Data/") + filename);
Note that this code will remove the extension if a file already exists. See C#: How would you make a unique filename by adding a number? for a better implementation.

Relative path not working while accessing a sqlite Database through C#

I am creating a Excel Addin through which i want to access a database. code is as follows
[ExcelFunction("My First Excel-DNA Function")]
public static string GreetFunction(string name)
{
GetConnection();
return "Hello" + " " + name;
}
public static void GetConnection()
{
//db = new SQLiteConnection("Data Source="+System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase)+"\\Database\\XLSQLiteDemo.sqlite");
db = new SQLiteConnection("Data Source=Database/XLSQLiteDemo.sqlite");
try
{
db.Open();
cmd = db.CreateCommand();
System.Windows.MessageBox.Show("Connection created");
}
catch (SQLiteException ex)
{
System.Windows.MessageBox.Show(ex.ToString());
}
}
so when i give absolute path like c:/test/firstlibrary.../XLSQLiteDemo.sqlite it works.
but when i use relative path like db = new SQLiteConnection("Data Source=Database/XLSQLiteDemo.sqlite");
it throws an exception: unable to open database file error code 14.
the code which is in comment i.e.
//db = new SQLiteConnection("Data Source="+System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase)+"\\Database\\XLSQLiteDemo.sqlite");
also doesn't work i.e. it calculates the absolute path but when i tried to debug; debugging is automatically terminated after db.Open();
and output in excel sheet is also #Value which indicates some error.
#adrino may be the "file" word in your string is the problem.remove it.
string relativePath = #"Database\XLSQLiteDemo.sqlite";
string currentPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
string absolutePath = System.IO.Path.Combine(currentPath, relativePath);
absolutePath=absolutePath.Remove(0, 6);//this code is written to remove file word from absolute path
string connectionString = string.Format("Data Source={0}", absolutePath);
this works on my machine.tell me if its correct.

reading Html file through OLEDB fails

i am trying to read html file through OLEDB reader using following code
DataTable dTable;
string strDataSource = "";
string strDBFile = "";
long intPos = 0;
strDataSource = mstrFilePath;
dTable = new DataTable();
mCon = new System.Data.OleDb.OleDbConnection();
mCon.ConnectionString = ("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + openFileDialog1.FileName + ";Extended Properties=\"HTML Import;HDR=NO;IMEX=1\";");
if (mCon.State == ConnectionState.Closed)
{
mCon.Open(); // gettting failed here
}
dTable = mCon.GetSchema("Tables");
bSelectionChanged = true;
lstTables.Items.Clear();
foreach (DataRow DRow in dTable.Rows)
{
if (DRow["TABLE_TYPE"].ToString() == "TABLE" || DRow["TABLE_TYPE"].ToString() == "VIEW")
{
intPos = DRow["TABLE_NAME"].ToString().LastIndexOf("FilterDatabase");
lstTables.Items.Add(DRow["TABLE_NAME"]);
}
}
if (lstTables.Items.Count == 1)
{
lstTables.Visible = false;
grdSampleDataControl.Dock = DockStyle.Fill;
}
else
{
lstTables.Visible = true;
grdSampleDataControl.Dock = DockStyle.None;
}
bSelectionChanged = true;
dTable.Dispose();
mCon.Close();
openFileDialog1.Dispose();
It is getting failed here wiht 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.
But file is not opened anywhere ??
Edit
On debug, When it throws exception at mCon.Open(), If i press F10 compiler moves to next statement and run the programm succesfully. why it is so ??
This is happening because your Acccess Database file is open.
You can not keep file open, and do changes on that file dynamically.
While the program using that file is running, it tries to open that file.
But, if file is already open exclusively by user, then it fails.
Close the file, and then try to open the connection.
For other details on it, follow this DISCUSSION.

Categories

Resources