How to create exception for database file not found in c#

1.1k views Asked by At

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

2

There are 2 answers

1
Alberto On BEST ANSWER

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

if(!File.Exists("Z:\\test.accdb"))
    throw new FileNotFoundException();
3
Nithin Nayagam On
    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;
}