Tôi đang cố viết đối tượng vào chuỗi Xml và lấy chuỗi đó và lưu nó vào DB. Nhưng trước tiên, tôi cần phải nhận được chuỗi ...Đọc từ luồng bộ nhớ thành chuỗi
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;
}
Điều này dường như hoạt động, luồng được lấp đầy bằng byte. Nhưng khi tôi đến để đọc nó trở lại vào bộ đệm và sau đó vào chuỗi ... bộ đệm được làm đầy với '0'! Không chắc tôi làm gì ở đây.
thể trùng lặp của [Làm thế nào để bạn có được một chuỗi từ một MemoryStream?] (Http://stackoverflow.com/questions/78181/how-do-you-get-a-string-from -a-memorystream) – andyp