已安装应用程序的Visual Studio app.config文件中的数据库路径。

3
我在我的应用程序中使用本地数据库,当我通过安装程序包(使用 安装程序包)生成安装文件后,在安装程序后会出现数据库路径错误。 示例:
an attempt to attach an auto-named database for file....
//OR
The given path format is not supported

one

我尝试在app.config文件中编辑数据库路径,但每次都失败了。默认情况下,我的代码行是这样的:

<add name="SampleDatabaseWalkthrough.Properties.Settings.SampleDatabaseConnectionString"
            connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\SampleDatabase.mdf;Integrated Security=True"
            providerName="System.Data.SqlClient" />

我的应用程序安装在C:\Program Files (x86)\App_Folder\Setup中。请注意,未来用户可能会将其安装在自定义路径中,因此我需要一种获取已安装应用程序动态路径的方法。

我的问题是:如何获取应用程序安装路径以替换此部分AttachDbFilename=|DataDirectory|\SampleDatabase.mdf

2个回答

2
您可以尝试使用AppDomain.CurrentDomain.SetData方法来更改您的mdf文件路径。
由于我不知道您是如何发布winform项目的。
我建议您使用Clickonce进行发布。
首先,请将您的mdf文件包含在项目中。
其次,在发布后,您可以尝试以下代码来更改安装路径。
 private void Form1_Load(object sender, EventArgs e)
            {
                if(System.Deployment.Application.ApplicationDeployment.IsNetworkDeployed)
                {
                    string path = ApplicationDeployment.CurrentDeployment.DataDirectory; //Get installed path
                    AppDomain.CurrentDomain.SetData("DataDirectory", path);//set the DataDirectory 
                }
            }

最后,基于我的测试,在将mdf文件发布并安装到另一台计算机后,我可以获取其中的信息。


我正在使用软件包安装程序(Visual Studio扩展)创建安装文件。我是否应该手动将数据库文件添加到我的安装文件中,还是它会自动包含在内? - mafortis
@mafortis,根据我的研究,你需要手动在安装文件中添加db文件。可以参考以下链接:在安装项目中包含文件夹 - Jack J Jun
嗨,我尝试了您链接中的被接受的答案,但我在“视图”>“文件系统”视图中找不到任何文件系统。 - mafortis
那么我只需要在那里选择我的mdf文件吗? - mafortis
没有人回复我的问题吗? - mafortis
显示剩余6条评论

0
在生产模式下,|DataDirectory| 指的是 'bin' 目录,而不是 'app_data'。如果您将 .mdf 文件放在 app_data 目录中,则可以像这样更改它:|DataDirectory|\SampleDatabase.mdf 改为 |DataDirectory|\app_data\SampleDatabase.mdf
<add name="SampleDatabaseWalkthrough.Properties.Settings.SampleDatabaseConnectionString"
        connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\app_data\SampleDatabase.mdf;Integrated Security=True"
        providerName="System.Data.SqlClient" />

更新1:

我正在发送一些代码。我只想给你一个想法。您可以根据自己的情况进行更改。

private void Form1_Load(object sender, EventArgs e)
{
    if (!IsExist())
    {
        CreateDatabase();
        CreateTables();
    }
}

// Create the Database
private void CreateDatabase()
{
    string basePath = Environment.CurrentDirectory;
    string mdfFile = "TestDatabase.mdf";
    string ldfFile = "TestDatabase_Log.mdf";
    string mdfFullPath = System.IO.Path.Combine(basePath, "Data", mdfFile);
    string ldfFullPath = System.IO.Path.Combine(basePath, "Data", ldfFile);

    SqlConnection myConn = new SqlConnection("Server=.;Data Source=(LocalDB)\\MSSQLLocalDB;Integrated security=SSPI;database=master");
    string str = "CREATE DATABASE TestDatabase ON PRIMARY " +
            "(NAME = TestDatabase, " +
            $"FILENAME = '{mdfFullPath}', " +
            "SIZE = 2MB, MAXSIZE = 10MB, FILEGROWTH = 10%)" +
            "LOG ON (NAME = MyDatabase_Log, " +
            $"FILENAME = '{ldfFullPath}', " +
            "SIZE = 1MB, " +
            "MAXSIZE = 5MB, " +
            "FILEGROWTH = 10%)";


    SqlCommand myCommand = new SqlCommand(str, myConn);
    try
    {
        myConn.Open();
        myCommand.ExecuteNonQuery();
        MessageBox.Show("DataBase is Created Successfully", "MyProgram", MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
    catch (System.Exception ex)
    {
        MessageBox.Show(ex.ToString(), "MyProgram", MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
    finally
    {
        if (myConn.State == ConnectionState.Open)
        {
            myConn.Close();
        }
    }
}

// Create the tables and other stuff that you want
private void CreateTables()
{
    string conStr = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Data\TestDatabase.mdf;Integrated Security=True;Connect Timeout=30";

    SqlConnection myConn = new SqlConnection(conStr);
    string str = @"CREATE TABLE [dbo].[TestTable]
                    (
                        [Id] INT NOT NULL PRIMARY KEY, 
                        [Test] NVARCHAR(50) NULL
                    )";

    SqlCommand myCommand = new SqlCommand(str, myConn);
    try
    {
        myConn.Open();
        myCommand.ExecuteNonQuery();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString(), "MyProgram", MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
    finally
    {
        if (myConn.State == ConnectionState.Open)
        {
            myConn.Close();
        }
    }
}

// Check if there is the database
private bool IsExist()
{
    string basePath = Environment.CurrentDirectory;
    string mdfFile = "TestDatabase.mdf";
    string mdfFullPath = System.IO.Path.Combine(basePath, "Data", mdfFile);

    return System.IO.File.Exists(mdfFullPath);
}

谢谢您的回答,我有一个与Jack相同的问题,我是否需要将我的mdf文件复制到我的安装程序中?如果需要复制,我是否需要在该mdf文件中进行任何更改?说实话,这是我的第一次尝试,我是完全的新手,因此我需要像步骤指南一样的指导来使其正常工作(正如我在赏金描述中所解释的那样)。谢谢。 - mafortis
没关系。如果不存在,你可以复制它或在第一次运行时创建它。而且你不需要改变任何东西。 我认为问题在于“路径”,而不是文件格式或其他任何东西。 - Saeid Amini
假设我没有复制我的数据库文件,你能指导我如何在第一次运行时生成一个吗?也许这可以解决我的问题。 - mafortis
您是否正在使用Microsoft SQL Server Database file 数据源? - Saeid Amini
我认为是这样(你提到了它的长名称,但我不知道),但它创建的文件是.mdf格式,并且是离线(本地)的。我没有使用任何在线数据库。 - mafortis
如果您正在使用像Entity Framework这样的ORM,您可以配置它以在不存在数据库时创建数据库。如果没有,您可以在第一次运行时创建您的数据库。只需查看这个有用的示例即可。 - Saeid Amini

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接