[英]Writing a memory stream to a file
我尝试将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();
}
有一个非常方便的方法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();
}
}
另外,您不必关闭fs
因为它位于using语句中,并且将在结尾处处理。
问题与文件流/内存流无关。 问题在于DataContractJsonSerializer
是OPT IN串行器。 您需要将[DataMemberAttribute]
添加到需要在myClass
上序列化的所有属性。
[DataContract]
public class myClass
{
[DataMember]
public string Foo { get; set; }
}
这行看起来有问题:
ms.Read(ms.ToArray(), 0, (int)ms.Length);
此时,您不需要读取任何内容到内存流中,尤其是在编写代码以将ms读入ms时。
我非常有信心,只需删除此行即可解决您的问题。
//重置流的位置
ms.Position = 0;
//然后复制到文件流
ms.CopyTo(fileStream);
using (var memoryStream = new MemoryStream())
{
...
var fileName = $"FileName.xlsx";
string tempFilePath = Path.Combine(Path.GetTempPath() + fileName );
using (var fs = new FileStream(tempFilePath, FileMode.Create, FileAccess.Write))
{
memoryStream.WriteTo(fs);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.