Connection string with relative path to the database file

后端 未结 10 618
暗喜
暗喜 2020-11-28 07:20

I load data from sdf database in winforms App. I use full path to the database file . Example :

conn = new SqlCeConnection

{

ConnectionString =\"Data Sou         


        
相关标签:
10条回答
  • 2020-11-28 07:50

    In your config file give the relative path

    ConnectionString = "Data Source=|DataDirectory|\Database.sdf";
    

    Change the DataDirectory to your executable path

    string path = AppDomain.CurrentDomain.BaseDirectory;
    AppDomain.CurrentDomain.SetData("DataDirectory", path);
    

    If you are using EntityFramework, then you can set the DataDirectory path in your Context class

    0 讨论(0)
  • 2020-11-28 07:56
       <?xml version="1.0"?>  
    <configuration>  
      <appSettings>  
        <!--FailIfMissing=false -->  
        <add key="DbSQLite" value="data source=|DataDirectory|DB.db3;Pooling=true;FailIfMissing=false"/>  
      </appSettings>  
    </configuration>  
    
    0 讨论(0)
  • 2020-11-28 07:59

    Relative to what, your application ? If so then you can simply get the applications current Path with :

    System.Environment.CurrentDirectory 
    

    And append it to the connection string

    0 讨论(0)
  • 2020-11-28 07:59

    I did this in the web.config file. I added to Sobhan's answer, thanks btw.

    <connectionStrings>
        <add name="listdb" connectionString="Data Source=|DataDirectory|\db\listdb.sdf"/>
      </connectionStrings>
    

    Where "db" becomes my database directory instead of "App_Data" directory.

    And opened normally with:

    var db = Database.Open("listdb");

    0 讨论(0)
  • 2020-11-28 08:00

    After several strange errors with relative paths in connectionstring I felt the need to post this here.

    When using "|DataDirectory|" or "~" you are not allowed to step up and out using "../" !

    Example is using several projects accessing the same localdb file placed in one of the projects.

    " ~/../other" and " |DataDirectory|/../other" will fail

    Even if it is clearly written at MSDN here the errors it gave where a bit unclear so hard to find and could not find it here at SO.

    0 讨论(0)
  • 2020-11-28 08:00

    Would you please try with below code block, which is exactly what you're looking for:

    SqlConnection conn = new SqlConnection
    {
        ConnectionString = "Data Source=" + System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase) + "\\Database.sdf"
    };
    
    0 讨论(0)
提交回复
热议问题