Friday, September 18, 2009

How to Create a MS-Access DataBase file by Clicking a button in C#.Net?



string fpath=null;

private void button2_Click(object sender, EventArgs e)
{
fpath="D:\\xyz.mdb";

if (System.IO.File.Exists(fpath))
fpath = "D:\\xyz-" + DateTime.Now.ToString("dd-mm-yy") + ".mdb";

CreateDatabase(fpath); //CreateDataBase method Call
System.Diagnostics.Process.Start(fpath); //Opens the Created File
}

public static bool CreateDatabase(string fullFilename)
{
bool succeeded = false;
try
{
string newDB = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fullFilename;
Type objClassType = Type.GetTypeFromProgID("ADOX.Catalog");

if (objClassType != null)
{
object obj = Activator.CreateInstance(objClassType);

// Create MDB file
obj.GetType().InvokeMember("Create", System.Reflection.BindingFlags.InvokeMethod, null, obj,
new object[] { "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + newDB + ";" });

succeeded = true;

// Clean up
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
}
catch (Exception ex)
{
//Tools.ShowMessage("Could not create database file: " + fullFilename + "\n\n" + ex.Message, "Database Creation Error");
MessageBox.Show(ex.ToString());
}
return succeeded;
}

No comments:

Post a Comment

Followers