通过C#访问sqlite数据库时相对路径不起作用

时间:2014-06-30 07:44:38

标签: c# sqlite

我正在创建一个Excel Addin,我想通过它来访问数据库。代码如下

    [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());       
        }
    }

所以当我给出像c:/test/firstlibrary.../XLSQLiteDemo.sqlite这样的绝对路径时,它就可以了。

但是当我使用db = new SQLiteConnection("Data Source=Database/XLSQLiteDemo.sqlite");

之类的相对路径时

它抛出异常:unable to open database file error code 14. 评论中的代码,即

//db = new SQLiteConnection("Data Source="+System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase)+"\\Database\\XLSQLiteDemo.sqlite");

也不起作用,即它计算绝对路径,但是当我试图调试时;调试在db.Open();后自动终止 excel表中的输出也是#Value,表示存在错误。

1 个答案:

答案 0 :(得分:1)

@adrino可能是"文件"你的字符串中的单词是问题。删除它。

       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); 

这适用于我的机器。如果正确的话,请告诉我。

相关问题