【问题标题】:Why doesn't DataDirectory change on run time为什么 DataDirectory 在运行时不改变
【发布时间】:2014-09-21 21:45:46
【问题描述】:

我正在尝试使用 w winform c# 应用程序连接到本地数据库 当我将连接字符串设置为数据时:Source=C:\Users\PACKARD BELL\documents\visual studio 2010\Projects\GestionStock\MyApp\Mydb.sdf
它工作正常,但是当我将它设置为Data Source=|DataDirectory|\Mydb.sdf 它不起作用 我试图用控制台中的数据目录变量打印连接字符串,我发现它没有改变

我希望连接字符串随着应用程序文件夹的位置而改变

我该怎么做? 在此先感谢

【问题讨论】:

  • 那不是 %data directory% 什么的吗?
  • 是的 |DataDirectory|但它不会改变

标签: c# winforms connection-string local-database


【解决方案1】:

根据MSDN

|DataDirectory|:这是通过AppDomain.SetData("DataDirectory", objValue) 方法设置的值。一个 ASP.NET 应用程序解析 |DataDirectory|到“/app_data”文件夹。

本质上,如果您使用|DataDirectory| 值,您的数据库必须存在于项目的App_Data\ 目录中。您可以更改默认值,但实际上这只会使其他可能期望默认行为的开发人员感到困惑。

所以,而不是

Source=C:\Users\PACKARD BELL\documents\visual studio 2010/Projects\GestionStock\MyApp\Mydb.sdf,

应该是

Source=C:\Users\PACKARD BELL\documents\visual studio 2010\Projects\GestionStock\MyApp\App_Data\Mydb.sdf

【讨论】:

  • 我确实将我的 sdf 文件放在 App_Data 目录中仍然不起作用
【解决方案2】:

但是文件夹 App_Data 中的 sdf 文件

【讨论】:

  • 请问如何使用?
  • 只需在您的项目中创建一个名为 App_data 的文件夹,或者您可以在解决方案资源管理器中右键单击项目时从空间文件夹菜单中进行选择。
【解决方案3】:

这是我写的 article 的一个片段:

// What's the name of the file you want to work with
var file_name = "parse_me.txt";

// Let's assume you're working with the file on your desktop
var path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);

// This is needed to "paste" the dir and the file name (it'll add the "\" basically).
var file_location = Path.Combine(path,file_name);

// Now you can do:
string[] read_all_lines = System.IO.File.ReadAllLines(file_location);

假设你有文件,它应该可以工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-06
    • 2015-10-14
    • 2014-11-06
    • 2019-01-11
    • 2012-07-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多