我需要能够在 app.config 文件中定义日期。如何执行此操作,然后使用 c# 检索它?
5 回答
将值存储在配置文件中:
<appSettings>
<add key="DateKey" value="2012-06-21" />
</appSettings>
然后检索您使用的值:
var value = ConfigurationSettings.AppSettings["DateKey"];
var appDate = DateTime.Parse(value);
在 Visual Studio 中使用设置很容易。只需通过打开项目的属性来添加设置,然后转到Settings
并单击“项目不包含默认设置文件。单击此处创建一个。”。
转到设置并添加一个 DateTime 并定义您的date
.
要访问代码中的设置,您只需执行此操作。
DateTime myDate = Properties.Settings.Default.MyDate;
Not sure If I fully understand your question. I think that you want to:
You can define date in your app.config in the appSettings section:
<appSettings>
<add key="DateX" value="21/06/2012"/>
</appSettings>
And retrieve AppSettings entry by doing something similar to this:
Datetime dateX;
System.Configuration.Configuration rootWebConfig1 = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(null);
if (rootWebConfig1.AppSettings.Settings.Count > 0)
{
System.Configuration.KeyValueConfigurationElement customSetting = rootWebConfig1.AppSettings.Settings["DateX"];
if (customSetting != null)
{
dateX = Datetime.Parse(customSetting.Value);
}
}
You can check this MSDN link for more help.
假设您指的是<appSettings>
元素,那么您一开始就没有运气:每个键都与一个字符串值相关联。
因此,您可以看到您只需将 DateTime 值序列化为字符串,然后在读回时将其解析回来。
如果您不关心您的 app.config 被人类在记事本中编辑,那么我会将 64 位刻度值存储为字符串整数:
ConfigurationManager.AppSettings["date"] = myDateTime.Ticks.ToString(CultureInfo.InvariantCulture);
通过这样做读回来:
Int64 ticks = Int64.Parse( ConfigurationManager.AppSettings["date"], NumberStyles.Integer, CultureInfo.InvariantCulture );
DateTime myDateTime = new DateTime( ticks );
但是,如果您确实想让它易于阅读,请使用往返选项:
// Serialise
ConfigurationManager.AppSettings["date"] = myDateTime.ToString("o"); // "o" is "roundtrip"
// Deserialise
DateTime myDateTime = DateTime.Parse( ConfigurationManager.AppSettings["date"], NumberStyles.Integer, CultureInfo.InvariantCulture ) );
几点注意事项:
- 我的代码是建议性的和粗糙的。实际上,您首先要确保所有 DateTime 实例都采用 UTC,然后在必要时应用时区偏移量。
- 您将首先检查 AppSettings 是否包含名为“date”的键,如果不包含则返回默认或零等效答案。
- 您还应避免使用 .Parse 方法并改用 TryParse 并根据您的应用程序处理错误情况。
however you want! I mean, a string, but beyond that your options are limitless. If you wanted to, you could store it as a children's book about a date. Just a matter of parsing it wherever you need to use it. But I'd suggest looking into DateTime.ToLongDateString in C# code somewhere, learning that pattern, and storing it like that.