private void timGetDB_Tick(object sender, EventArgs e)
{//timer
timGetDB.Enabled = false;
string dbPath = GetDBPath();
while (true)
{
if (dbPath == "0")
{
//说明数据库和ini文件都不存在
ofdDB.InitialDirectory = Application.StartupPath;
DialogResult opdr=ofdDB.ShowDialog();
if (opdr == DialogResult.OK)
{
if ((dbPath = ofdDB.FileName) != null)
if (FileExist(dbPath))
{
//IniFile ini = new IniFile(dbPath);
INIFile ini = new INIFile(Application.StartupPath + "//cowa.ini");
ini.Write("DB", "DBName", dbPath);
break;
}
}
else if (opdr == DialogResult.Cancel)
{
this.Close();
return ;
}
}
//数据库文件就在程序文件夹里
if (dbPath.Substring(dbPath.Length - 3, 3) == "mdb")
break;
if (dbPath.Substring(dbPath.Length - 3, 3) == "ini")
{
INIFile ini = new INIFile(dbPath);
dbPath = ini.ReadString("DB", "DBName");
if (!FileExist(dbPath))
{
//说明ini文件里存的路径是错的,ini文件将被删除
dbPath = "0";
ini.DeleteFile();
continue;
}
}
}
try
{
//到此处dbPath 为正确路径,以下可进行数据库操作
}
catch (Exception err)
{
MessageBox.Show("数据库操作失败", "错误");
}
}
/// <summary>
/// 通过程序文件夹中的INI文件获取数据库路径,
/// 先在程序文件夹中寻找数据库,再寻找INI文件
/// </summary>
/// <returns>返回数据库或INI文件路径,如果二者都不存在,则返回"0"</returns>
private string GetDBPath()
{//
string dbPath=Application.StartupPath + "//system.mdb" ;
string iniPath = Application.StartupPath + "//cowa.ini";
bool dbEx=FileExist(dbPath), iniEx=FileExist(iniPath);
if (dbEx)
return dbPath;
else if (iniEx)
return iniPath;
else if (!dbEx && !iniEx)
return "0";//no db, no ini;
return dbPath;
}
/// <summary>
/// 判断文件是否存在
/// </summary>
/// <param name="path">存在返回true,不存在或路径错误返回false</param>
/// <returns></returns>
private bool FileExist(string path)
{
try
{
FileInfo fi = new FileInfo(path);
if (fi.Exists)
return true;
else
return false;
}
catch (Exception err)
{
return false;
}
}
//INIFile类的内容参见另一篇文章:http://blog.csdn.net/ltolll/archive/2008/01/23/2061723.aspx