我曾尝试将数据以json格式作为字符串检索并写入文件,效果非常好。现在我正在尝试使用MemoryStream做同样的事情,但文件中没有任何实际数据,只是 [{},{},{},{},{}]。
我的问题是 - 我该如何检查数据是否正确地传输到内存流中,或者问题发生在其他地方。我知道myList确实包含数据。
这是我的代码:
MemoryStream ms = new MemoryStream();
DataContractJsonSerializer dcjs = new DataContractJsonSerializer(typeof(List<myClass>));
dcjs.WriteObject(ms, myList);
using (FileStream fs = new FileStream(Path.Combine(Application.StartupPath,"MyFile.json"), FileMode.OpenOrCreate))
{
ms.Position = 0;
ms.Read(ms.ToArray(), 0, (int)ms.Length);
fs.Write(ms.ToArray(), 0, ms.ToArray().Length);
ms.Close();
fs.Flush();
fs.Close();
}
ms.Read(ms.ToArray(), 0, (int)ms.Length);
这句代码为什么要读取内存流并覆盖dcjs.WriteObject
写入的内容呢?这似乎是你的问题所在,不要重置流位置并覆盖自身。 - Ron Beyer