我想寫一個對象到一個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'!不知道我在這裏做錯了什麼人。
可能重複[你如何從一個MemoryStream的字符串?](http://stackoverflow.com/questions/78181/how-do-you-get-a-string-from -a-memorystream) – andyp