尝试将 JSON 对象保存到文件中,并将该文件作为应用程序的参数传递。
@Wildcard27:
这是一个实际用例,用于创建 Windows 任务,该任务用于教职员工学位应用程序。JSON 只是我正在使用的 DTO 的简单序列化。
在对 JSON 进行序列化时,只需将其保存到空白文件中,并赋予其适当的名称,以使其唯一。
private string CreateTaskConfigurationFile(string taskName, EquipmentEventExtended eventData, string host)
{
List<Change> changes = new List<Change>
{
new Change(MailConstants.EventName,eventData.EventName),
new Change(MailConstants.Deadline, eventData.DateTo.Value.ToShortDateString()),
new Change(MailConstants.EventDetails, eventData.EventDetails),
new Change(MailConstants.Link,$"{host}/Inventory/Details/{eventData.InventoryId}")
};
MailTaskModel mtm = new MailTaskModel
{
Body = MailConstants.UpdateTemplate(MailConstants.TaskMailTemplate, changes),
Subject = "[Reminder] Upcoming Event needs your attention",
ToAddress = "abcdef@gmail.com",
IsHtml = true
};
var fileName = string.Format(@"E:\{0}.json", taskName);
using (StreamWriter file = File.CreateText(fileName))
{
JsonSerializer js = new JsonSerializer();
js.Serialize(file, mtm);
}
return fileName;
}
然后将文件路径作为参数提供给控制台应用程序:
static void Main(string[] args)
{
var configFilePath = args[0];
var mailConfig = LoadConfigurationFile(configFilePath);
MailManager manager = new MailManager(mailConfig.ToAddress, mailConfig.FromAddress,mailConfig.Subject, mailConfig.Body,mailConfig.IsHtml);
manager.SendMail();
}
private static MailTaskModel LoadConfigurationFile(string configurationFilePath)
{
MailTaskModel mailConfig;
using(var sr = new StreamReader(configurationFilePath))
{
string json = sr.ReadToEnd();
mailConfig = JsonConvert.DeserializeObject<MailTaskModel>(json);
}
return mailConfig;
}
你可以使用类似于以下方式的工具:
ConsoleApplication.exe -yourFilePath
我已经移除了对空值的冗余检查,以便更加清晰。