Hi everyone i can't set a relative path to open my database, the project is structured in this mood
projectname
db/acces.db
info/try.cs
This is the code inside try.cs with which i should open the database, obviously if I put the full path it goes:
try {
using (SQLiteConnection conn = new SQLiteConnection(@"data source="db/access.db")
{
conn.Open();
using (SQLiteCommand fmd = conn.CreateCommand()){
fmd.CommandText = @"SELECT * FROM 'test';
fmd.CommandType = CommandType.Text;
SQLiteDataReader r = fmd.ExecuteReader();
while (r.Read())
Debug.Writeline("foo");
conn.Close();
}
}
catch (Exception e){
Debug.WriteLine("Errors");
}
I should take the path of the acces.db file, not complete but relative to my project, to be set in data source, how should i do?
CodePudding user response:
You can use something like this:
using System.IO;
var connection = "Data Source=" Path.Combine(Directory.GetCurrentDirectory(), "db\\access.db")
try {
using (SQLiteConnection conn = new SQLiteConnection(connection)
{
conn.Open();
using (SQLiteCommand fmd = conn.CreateCommand()){
fmd.CommandText = @"SELECT * FROM 'test';
fmd.CommandType = CommandType.Text;
SQLiteDataReader r = fmd.ExecuteReader();
while (r.Read())
Debug.Writeline("foo");
conn.Close();
}
}
catch (Exception e){
Debug.WriteLine("Errors");
}
CodePudding user response:
You said you should get something of type Data Source=C:\\Users\\mypc\\Documents\\tesrepo\\Myapp\\testApp\\db\\test.db
.
Here is how to get the correct path.
Project path:
Directory.GetParent(workingDirectory).Parent.FullName;
Add the path you want at the end: For example, the address of the 123.mp3
file in the music
folder here is:
string filepath = Path.Combine(projectDirectory "\\music\\123.mp3");
//Get db address
string workingDirectory = Environment.CurrentDirectory;
string projectDirectory = Directory.GetParent(workingDirectory).Parent.FullName;
string dbpath = Path.Combine(projectDirectory "\\db\\test.db");
dbpath
is what you want.
If you have any questions about my code, please add a comment below.
Updated:
You can import the updated file into the output directory through this operation.
Your path would work without any modification.