在尝试在service.cs文件中设置数据库的路径时,您是否知道如何在c#中设置本地目录的路径? (我在VS2010开发)
我开发了一个使用.mdf
(SQL Server)数据库的winforms程序。该程序通过SQL Server连接字符串与数据库通信。
我已经对mo的db路径进行了硬编码,但想知道如何指向当前目录。
我在网上看到了
AttachDbFilename =|DataDirectory|\Database.mdf
但它似乎对我不起作用,因为连接无法打开。
此外,我已尝试使用Environment.CurrentDirectory
,但CurrentDirectory
与{{1}}奇怪地不在命名空间中。
答案 0 :(得分:0)
如果文件位于同一个程序集文件夹中,则可以使用此
string folder = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.ConnectionStrings.ConnectionStrings["myCS"].ConnectionString = config.ConnectionStrings.ConnectionStrings["myCS"].ConnectionString.Replace("#folder#",folder);
config.Save(ConfigurationSaveMode.Full, true);
答案 1 :(得分:0)
转到解决方案资源管理器>>右键单击项目>>点击属性>>转到设置标签>>创建名称:MyConnectionString类型:(连接字符串)Scoper:应用程序
并选择数据库(Db应保存在您的| DataDirectory |和您的dblog中)>>选择那个DB。 >>保存它。
然后使用此代码进行连接 SqlCeConnection cnn = new SqlCeConnection(Properties.Settings.Default.MyConnectionString);
您必须提供命名空间:using System.Data.SqlServerCe;
希望这会解决。接受是否有效并关闭问题
答案 2 :(得分:0)
有一种方法可以通过对我有用的代码获取数据库的.mdf和.ldf,使用连接字符串打开连接到数据库,使用查询
准备SQL命令select physical_name from sys.database_files where type = 0
然后执行命令,顺便说一句,type = 0
用于mdf,而type = 1
用于ldf,您也可以直接在SSMS中使用此查询
这是示例代码,请记住您需要获取连接字符串
string _mdfCommand = "select physical_name from sys.database_files where type = 0";
string _ldfCommand = "select physical_name from sys.database_files where type = 1";
SqlCommand GetSQLData = new SqlCommand();
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
GetSQLData.CommandText = _mdfCommand;
GetSQLData.Connection = connection;
string mdf_Path= (string)GetSQLData.ExecuteScalar();
GetSQLData.CommandText = _ldfCommand;
GetSQLData.Connection = connection;
string ldf_Path= (string)GetSQLData.ExecuteScalar();
connection.Close();