Tôi muốn tuần tự hóa/de-serialize một đối tượng bằng cách sử dụng một chuỗi. Chỉ cần lưu ý, khi tôi serialize/de-serialize vào một tập tin tất cả mọi thứ hoạt động tốt. Những gì tôi đang cố gắng làm là lấy một chuỗi để tôi có thể lưu trữ nó trong cơ sở dữ liệu và sau đó kéo nó ra sau để hủy tuần tự hóa.protobuf-net Serialize thành chuỗi và lưu trữ trong cơ sở dữ liệu Sau đó, De Serialize
Đây là mã mà làm việc:
MemoryStream msTest = new MemoryStream();
Serializer.Serialize(msTest, registrationBlocks);
msTest.Position = 0;
List<RVRegistrationBlock> CopiedBlocks = new List<RVRegistrationBlock>();
CopiedBlocks = Serializer.Deserialize<List<RVRegistrationBlock>>(msTest);
Các "CopiedBlocks" đối tượng là cùng một danh sách đó là trong "registrationBlocks" Các công trình lớn, tất cả mọi thứ serialized/de-serialized. Tôi đang giữ mọi thứ trong luồng ở đây.
Dưới đây là đoạn code mà không hoạt động khi tôi cố gắng để có được một chuỗi tham gia:
MemoryStream msTestString = new MemoryStream();
Serializer.Serialize(msTestString, registrationBlocks);
msTestString.Position = 0;
StreamReader srRegBlock = new StreamReader(msTestString);
byte[] bytedata64 = System.Text.Encoding.Default.GetBytes(srRegBlock.ReadToEnd());
string stringBase64 = Convert.ToBase64String(bytedata64);
byte[] byteAfter64 = Convert.FromBase64String(stringBase64);
MemoryStream afterStream = new MemoryStream(byteAfter64);
List<RVRegistrationBlock> CopiedBlocksString = new List<RVRegistrationBlock>();
CopiedBlocksString = Serializer.Deserialize<List<RVRegistrationBlock>>(afterStream);
Trên dòng cuối cùng khi nó đi để deserialize, tôi nhận được một ngoại lệ: Ngoại lệ của loại 'Protobuf. ProtoException 'đã bị ném. Tôi không thể thâm nhập vào nó, ngoại lệ bên trong là vô giá trị. Tôi không thể hiểu tại sao nó lại làm.
Tôi chắc chắn đã thu hẹp nó xuống thực tế là khi tôi nhận được một chuỗi liên quan đến nó đi haywire. Tôi đang lưu trữ chuỗi trong một cơ sở dữ liệu trong một nvarchar (tối đa) đó là lý do tại sao tôi muốn chuỗi.
Mọi trợ giúp sẽ được đánh giá cao!
Tốt câu trả lời; có một tối ưu hóa * nhỏ * bạn có thể thực hiện nếu bạn muốn - 'Convert.ToBase64String (msTestString.GetBuffer(), 0, (int) msTestString.Length)' để tránh tạo thêm một 'byte []'. Nhưng nó sẽ làm việc "như là". –