How can I XML serialise to a memory stream and get the same results as if I'd serialised to a file stream?
I am working on an application that stores its documents in XML using the C# seria开发者_JAVA技巧lisation / deserialisation.
When the the user wants to perform a run in the application, we need to prompt the user to save the document if it has changed. (And also when the user tries to close the document.)
We evaluate whether the document has changed by comparing the object in memory to the document's file on disk. The object in memory is XML serialised to a MemoryStream, and this is compared to a stream for the file on disk.
My problem is that the files are identical apart from the XML header. The file on disk begins with
<?xml version="1.0"?>
whereas the MemoryStream (when written to a file on disk) begins with
"<?xml version="1.0" encoding="utf-8"?>"
So of course, the two streams do not compare. What am I doing wrong? How can I get the results to be the same regardless of the stream I'm using?
Having looked into this issue some time ago, I got the impression that it might be to do with stream encoding formats, and that in C# the MemoryStream uses a different default encoding format to strings. (Or something.)
The code that is serialising to file is:
/// <summary>
/// Serialises the workspace.
/// </summary>
/// <param name="stream">
/// The stream to serialise to.
/// </param>
private void Serialise(Stream stream)
{
stream.Seek(0, SeekOrigin.Begin);
DeflateStream compressingStream = new DeflateStream(stream, CompressionMode.Compress, true);
BufferedStream bufferedStream = new BufferedStream(compressingStream, 65536);
new XmlSerializer(typeof(Workspace)).Serialize(bufferedStream, this);
bufferedStream.Close();
compressingStream.Close();
}
The code that is serialising to memory is:
/// <summary>
/// Checks whether an object has changed since last save.
/// </summary>
/// <param name="storagePath">The path of the object.</param>
/// <param name="current">The current memory version of the object.</param>
/// <returns>Whether the object has changed since last save.</returns>
private static bool HasObjectChanged(string storagePath, object current)
{
Stream streamCurr = new MemoryStream();
DeflateStream compressingStream = new DeflateStream(streamCurr, CompressionMode.Compress, true);
...
new XmlSerializer(current.GetType()).Serialize(compressingStream, current);
Thanks for any help,
Luke.Try using a StreamWriter:
...
StreamWriter writer = new StreamWriter(bufferedStream);
new XmlSerializer(typeof(Workspace)).Serialize(writer, this);
writer.Close();
...
And:
...
StreamWriter writer = new StreamWriter(compressingStream);
new XmlSerializer(current.GetType()).Serialize(writer, current);
writer.Close();
...
精彩评论