Cod*_*ess 6 c# json memorystream
我已经尝试将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();
}
Run Code Online (Sandbox Code Playgroud)
Phi*_*aré 22
有一种非常方便的方法,Stream.CopyTo(Stream).
using (MemoryStream ms = new MemoryStream())
{
StreamWriter writer = new StreamWriter(ms);
writer.WriteLine("asdasdasasdfasdasd");
writer.Flush();
//You have to rewind the MemoryStream before copying
ms.Seek(0, SeekOrigin.Begin);
using (FileStream fs = new FileStream("output.txt", FileMode.OpenOrCreate))
{
ms.CopyTo(fs);
fs.Flush();
}
}
Run Code Online (Sandbox Code Playgroud)
此外,您不必关闭,fs因为它在using语句中,并将在最后处置.
| 归档时间: |
|
| 查看次数: |
41109 次 |
| 最近记录: |