![](/img/trans.png)
[英]C# How to get the User AppData folder, NOT AppData\Roaming?
[英]C# - How to install the Database in AppData directory?
我必須安裝我的窗口表單應用程序並將數據庫保留在AppData目錄中。 但是我無法在app.confing中建立數據庫的正確路徑。我在StackOverflow上找到了一些答案,然后嘗試以下方法。
<connectionStrings>
<add name="Default" connectionString="Driver={Microsoft Access Driver
(*.mdb)};AttachDbFileName=|DataDirectory|\HamaraPaisa.mdb"
providerName="System.Data.OleDb" />
</connectionStrings>
在我的Program.cs文件中:
static class Program
{
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
AppDomain.CurrentDomain.SetData("DataDirectory",
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData));
Application.Run(new Form1());
}
}
但是我仍然收到“對象引用未設置為對象實例”的異常,因為我沒有連接到數據庫。
如果使用ODBC驅動程序打開Microsoft Access數據庫,則正確的連接字符串為
OdbcConnection cn = new OdbcConnection(@"Driver={Microsoft Access Driver (*.mdb)};
Dbq=|DataDirectory|\HamaraPaisa.mdb");
如果您使用的是OleDb庫,則應將連接字符串寫為
OleDbConnection cn = new OleDbConnection(@"Provider=Microsoft.ACE.OleDb.12.0;
Data Source=|DataDirectory|\HamaraPaisa.mdb");
或者,如果您擁有32位應用程序和舊的(可預訪問的)2007 MDB文件,則可以使用
OleDbConnection cn = new OleDbConnection(@"Provider=Provider=Microsoft.Jet.OLEDB.4.0;
Data Source=|DataDirectory|\HamaraPaisa.mdb");
但是,我強烈建議您在Environment.SpecialFolder.ApplicationData內部創建您的個人數據文件夾,並且不要將另一個文件添加到已經擁擠的文件夾中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.