I have some code in PHp, which I am trying to redo in C#. The PHP code has something like fputs($file,serialize($val))
What could be the dot开发者_运维技巧 NET specifically C# equivalent of Serialize???
using (Stream stream = File.Open(filePath, FileMode.Create))
{
BinaryFormatter bformatter = new BinaryFormatter();
bformatter.Serialize(stream, myObject);
}
As with most things in .NET, there's many ways to get there depending on how you're planning to use it.
Ways I can think of in the .NET BCL:
- XmlSerializer as pointed out by Zach
- BinaryFormatter as RedFilter points out,
- WCF's DataContract XML/JSON Serializer
I like the WCF DataContract Serializer generally because I can choose either XML or JSON as needed, and I don't need to mark up my classes (.NET 3.5 SP1+) to make basic serialization work. I wrote a few helpers for this purpose: http://will.hughesfamily.net.au/20090309/net-35-helper-methods-serialize-objects-to-xml/
The Sharp Serialization Library worked for me when porting serialize calls from vBulletin to C#. But in the serialize
method I had to replace StringEncoding.GetByteCount(str)
by str.Length
because StringEncoding.GetByteCount
gave me the length + 1, which caused problems on deserialization using PHP. So the whole line should be
return sb.Append("s:" + str.Length + ":\"" + str + "\";");
.NET provides either binary or XML/SOAP serialization. See MSDN.
精彩评论