How do I retain database connectivity, with my project, when the source file path changes?

前端 未结 3 503
我在风中等你
我在风中等你 2021-01-07 11:38

I am using a Microsoft Access Database in my project; saved to the bin folder. What can I do, to ensure connectivity to that database, when the file path ch

相关标签:
3条回答
  • 2021-01-07 12:01

    I use this simple code and I can move the folder any where

    conString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=..\myDatabase.mdb"
    

    Make sure to save the access file in the bin folder for this connection string to work.

    0 讨论(0)
  • 2021-01-07 12:18

    Your connection string locates your database in a fixed position valid only on your PC.
    A simple workaround is to use the |DataDirectory| substitution string.

    con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" + 
                           "Data Source=|DataDirectory|\MP1.accdb"
    

    in this way, you can control the location of your database through code.
    Usually (for a desktop application) the |DataDirectory| substitution string points the same folder where you have installed your application, but you need to have permission to write there and any kind of active database requires write permissions on its files. So this is not the best location for database files.

    However you could change the location pointed by DataDirectory using code like this. (Of course put it BEFORE any attempt to talk to the database)

     ' Prepare a string pointing to a subfolder of the common application data 
     Dim appFolder = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData)
     Dim dbFolder = Path.Combine(appFolder, "MyAppFolder")
    
     ' Create the folder if it doesn't exist.
     Directory.CreateDirectory(dbFolder)
    
     ' Change the substitution string kept by DataDirectory
     AppDomain.CurrentDomain.SetData("DataDirectory", dbFolder)
    

    Now the target directory for your database will be C:\programdata\myappfolder where your application has read/write permissions

    More info on DataDirectory

    Where is DataDirectory
    DataDirectory where is documented

    0 讨论(0)
  • 2021-01-07 12:18

    Yea, you should use:

    con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & Application.StartupPath & "MP1.accdb"
    

    And have the database file in the same folder as you startup .exe...

    0 讨论(0)
提交回复
热议问题