通过网络连接到SQLite DB

问题描述 投票:2回答:1

我目前正在映射网络驱动器并以这种方式连接到文件(Z:\ Data \ Database.db)。我希望能够在连接字符串中使用相对路径(\ server \ Data \ Database.db)但它给我一个SQLite错误“无法打开数据库文件”。 Directory.Exists(\\server\Data\Database.db);检查返回true。

以下是使用路径“\\ server”作为参数打开连接的尝试:

public static OpenDB(string dbPath)
{
    using (SQLiteConnection conn = new SQLiteConnection($"Data Source={Path.Combine(dbPath, "Data\\Database.db")}"))
    {
        if (dbPath != null && dbPath != "")
        {
            try
            {
                conn.Open();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Unable to Open Database", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}
c# sqlite sqlconnection
1个回答
0
投票

这是我使用的解决方案。这是来自jdwengShawn的建议的组合。首先,我将路径dbPath作为管理共享驱动器。从那里我使程序从管理共享中创建数据库的临时本地副本:

private static void MakeTempDatabaseCopy(string dbPath, string exePath)
{
    try
    {
        File.Copy(Path.Combine(dbPath, "Data", "Database.db"), Path.Combine(exePath, "Temp", "Database.db"), true);
        FileInfo directoryInfo = new FileInfo(Path.Combine(exePath, "Temp", "Database.db"));
        directoryInfo.Attributes = FileAttributes.Temporary;
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, "Error Retrieving Database", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

之后,所有方法都可以从本地副本中读取。由于File.Copy()使用布尔值,因此需要刷新数据库的任何内容都可以使用管理共享中的新副本覆盖本地副本。希望这可以帮助!

© www.soinside.com 2019 - 2024. All rights reserved.