我用c#编写了一个示例,但是当我使用相对连接字符串时,它不会将数据保存到数据库中,甚至不会产生任何异常或错误:
private void AddButton_Click(object sender, EventArgs e)
{
using (DataBaseModelDataContext DB = new DataBaseModelDataContext(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\DataBase.mdf;Integrated Security=True;User Instance=True"))
{
Person person = new Person { Name=NameField.Text,LastName=LastNameField.Text};
DB.Persons.InsertOnSubmit(person);
DB.SubmitChanges();
MessageBox.Show("Add successfully");
}
}
但是当我更改连接字符串时,它可以工作:
using (DataBaseDataContext DB = new DataBaseDataContext(@"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Herald\Documents\Visual Studio 2010\Projects\LinqToSql\LinqToSql\DataBase.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True")
但我需要使用相对连接字符串我应该怎么做:
答案 0 :(得分:1)
您需要获取当前目录并将其映射到字符串中。
path = New Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath;
path = IO.Path.GetDirectoryName(path);