【发布时间】:2023-01-27 02:55:30
【问题描述】:
我设法在这里创建了最小的可重现示例:
internal class Program
{
static void Main(string[] args)
{
Program p = new Program();
Cache sc = new Cache();
sc.Enabled = true;
sc.Path = @"C:\File.txt";
p.WriteToJsonFile("Cache.json", sc);
}
private void WriteToJsonFile<T>(string filePath, T objectToWrite, bool append = false) where T : new()
{
TextWriter writer = null;
try
{
var contentsToWriteToFile = JsonSerializer.Serialize(objectToWrite);
writer = new StreamWriter(filePath, append);
writer.Write(contentsToWriteToFile);
}
finally
{
if (writer != null)
writer.Close();
}
}
internal class Cache
{
public string Path = string.Empty;
public bool Enabled;
}
}
文件Cache.json 已创建,但它只包含{},这意味着这些属性被忽略且未保存。也许 WriteToJsonFile 方法有问题,但在某些情况下它似乎有效。它在其中一个 stackoverflow 问题中得到了批准的答案。
【问题讨论】: