【发布时间】:2012-05-13 20:13:17
【问题描述】:
我正在尝试将一个对象写入一个 Xml 字符串并获取该字符串并将其保存到数据库中。但首先我需要得到字符串...
private static readonly Encoding LocalEncoding = Encoding.UTF8;
public static string SaveToString<T> (T settings)
{
Stream stream = null;
TextWriter writer = null;
string settingsString = null;
try
{
stream = new MemoryStream();
var serializer = new XmlSerializer(typeof(T));
writer = new StreamWriter(stream, LocalEncoding);
serializer.Serialize(writer, settings);
var buffer = new byte[stream.Length];
stream.Read(buffer, 0, (int)stream.Length);
settingsString = LocalEncoding.GetString(buffer);
}
catch (Exception ex)
{
// If the action cancels we don't want to throw, just return null.
}
finally
{
if (stream != null)
stream.Close();
if (writer != null)
writer.Close();
}
return settingsString;
}
这似乎有效,流被字节填充。但是当我把它读回缓冲区然后读入字符串时......缓冲区充满了'0'!不知道我在这里做错了什么。
【问题讨论】:
标签: c# xml-serialization xmlserializer memorystream