How to use relative paths to connect to a database in C#

In C#, you can use relative paths to connect to a database. Relative paths are based on the working directory of the current application.

Firstly, you can use the Environment.CurrentDirectory method to obtain the working directory of the current application. Then, you can place the database file in a subdirectory within the working directory.

Below is an example code for connecting to an SQLite database, using a relative path.

using System;
using System.Data.SQLite;

namespace DatabaseExample
{
    class Program
    {
        static void Main(string[] args)
        {
            string databasePath = "data/mydatabase.db";
            string connectionString = $"Data Source={databasePath};Version=3;";

            using (var connection = new SQLiteConnection(connectionString))
            {
                try
                {
                    connection.Open();

                    // 连接成功后可以执行其他数据库操作

                    Console.WriteLine("连接成功");
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"连接失败:{ex.Message}");
                }
            }
        }
    }
}

In the above example, the database file mydatabase.db is placed in the data subdirectory within the application’s working directory. The connection string is then constructed using the relative path data/mydatabase.db.

Please note that SQLite database is used as an example here, the format of the connection string may vary for other databases.

Additionally, if you need to debug code in Visual Studio, the working directory of the application is typically the directory where the solution file is located. You can adjust the working directory by setting the “Working Directory” in the project’s property settings under the “Debug” tab.

广告
Closing in 10 seconds
bannerAds