0

I have to connect my code to the access database but mainly, have to provide clear exception if that database file is not located in given location (like file not found). For this code :

string connStr =( @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Z:\test.accdb;Persist Security Info=False");
OleDbConnection conn1 = new OleDbConnection();
conn1.ConnectionString = connStr;             

OleDbCommand cmd = conn1.CreateCommand();
cmd.CommandText = "INSERT INTO customer (id, name)" + " VALUES('3', 'C');";

conn1.Open();
cmd.ExecuteNonQuery();

I want to display message if test database is not present there. What can I do ? please suggest. thank you

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
userabc55478
  • 61
  • 1
  • 8
  • 3
    Use [File.Exists(path_to_your_database_file)](http://msdn.microsoft.com/en-us/library/system.io.file.exists.aspx) – Steve Sep 07 '13 at 13:20
  • 2
    If your database file doesn't exists, the `conn1.Open()` will throw `Exception` and you can catch them and show corresponding message. – Hamlet Hakobyan Sep 07 '13 at 13:23
  • As other's have File.Exists is your best bet. Connect exception would also get thrown on say wrong password or ACL and it's really irritating as a user to be presented with a message saying a file doesn't exist when it does. – Tony Hopkinson Sep 07 '13 at 13:31

2 Answers2

2

I think you can use the static method File.Exists:

if(!File.Exists("Z:\\test.accdb"))
    throw new FileNotFoundException();
Alberto
  • 15,626
  • 9
  • 43
  • 56
  • 1
    A possible improvement to @Alberto's answer would be to create your own Custom Exception(s) instead of using FileNotFound. Might also be worth checking if the user has write access to the mdb as well, as Exists but readonly isn't going to be useful for an insert. – Tony Hopkinson Sep 07 '13 at 13:36
1
    try
{
string connStr =( @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Z:\test.accdb;Persist Security Info=False");
OleDbConnection conn1 = new OleDbConnection();
conn1.ConnectionString = connStr;             

OleDbCommand cmd = conn1.CreateCommand();
cmd.CommandText = "INSERT INTO customer (id, name)" + " VALUES('3', 'C');";

conn1.Open();
cmd.ExecuteNonQuery();
}
catch(Exception e)
{
 //print the message you want;
}
Nithin Nayagam
  • 458
  • 2
  • 5
  • 9
  • OleDbException would be a better choice in the catch – Tony Hopkinson Sep 07 '13 at 13:38
  • @TonyHopkinson yes i agree but i dont think the OP needs information about the kind of exception as he only wants to print a custom message. – Nithin Nayagam Sep 07 '13 at 13:40
  • Sorry can't agree. Always trap the most restrictive exception you can afford. Your code would swallow anything wrong in the try block. forgetting to instance the connection for example. Just a habit worth developing that's all. – Tony Hopkinson Sep 07 '13 at 14:40