Saving multiple objects to binary file - c#

I'm trying to save multiple object that the user create to a binary file. So far I am able to create a binary file of one object.
public class BinSerializerUtility
{
public void BinaryFileSerialize(object obj, string filePath)
{
FileStream fileStream = null;
try
{
fileStream = new FileStream(filePath, FileMode.Create);
BinaryFormatter b = new BinaryFormatter();
b.Serialize(fileStream, obj);
}
catch
{
throw;
}
finally
{
if (fileStream != null)
fileStream.Close();
}
}
MainForm:
private void SaveToFile(string filename)
{
for (int index = 0; index < animalmgr.Count; index++)
{
Animal animal = animalmgr.GetAt(index);
BinSerializerUtility BinSerial = new BinSerializerUtility();
BinSerial.BinaryFileSerialize(animal, filename);
}
}
private void mnuFileSaveAs_Click(object sender, EventArgs e)
{
//Show save-dialogbox
if(saveFileDialog1.ShowDialog() == DialogResult.OK)
{
string thefilename = saveFileDialog1.FileName;
SaveToFile(thefilename);
}
}
I'm not really sure how to make it so it can save multiple objects to binary file. Do you have any tips?
I did try the following:
public byte[] SerializeArray(object obj)
{
byte[] serializedObject = null;
MemoryStream memStream = null;
try
{
memStream = new MemoryStream();
BinaryFormatter binFormatter = new BinaryFormatter();
binFormatter.Serialize(memStream, obj);
memStream.Seek(0, 0); //set position at 0,0
serializedObject = memStream.ToArray();
}
finally
{
if (memStream != null)
memStream.Close();
}
return serializedObject; // return the array.
}
But the problem with it is that I don't know where to insert the fileName (The path)

You can modify BinaryFileSerialize to accept an array:
public void BinaryFileSerialize(object [] objs, string filePath). Then you can loop over that array to insert each item in the array:
FileStream fileStream = new FileStream(filePath, FileMode.Create);
BinaryFormatter b = new BinaryFormatter();
foreach(var obj in objs) {
b.Serialize(fileStream, obj);
}
SaveToFile function:
private void SaveToFile(string filename)
{
//Animal array
Animal [] animals = new Animal[animalmgr.Count];
for (int index = 0; index < animalmgr.Count; index++)
{
animals[index] = animalmgr.GetAt(index);
}
BinSerializerUtility BinSerial = new BinSerializerUtility();
BinSerial.BinaryFileSerialize(animals, filename);
}

Related

Opening a file with multiple objects

I'm trying to open and display a file that has multiple objects in it (array). I am able to open a file and display only the first object inside the file, but I want to be able to open and display all the object inside the file.
Here is how I tried it:
public T BinaryFileDeSerialize<T>(string filePath)
{
FileStream fileStream = null;
Object obj;
try
{
if (!File.Exists(filePath))
throw new FileNotFoundException("The file" + " was not found. ", filePath);
fileStream = new FileStream(filePath, FileMode.Open);
BinaryFormatter b = new BinaryFormatter(); obj = b.Deserialize(fileStream);
}
catch
{
throw;
}
finally
{
if (fileStream != null)
fileStream.Close();
}
return (T)obj;
}
MainForm:
private Animal ReadFile(string filename)
{
BinSerializerUtility BinSerial = new BinSerializerUtility();
Animal str = BinSerial.BinaryFileDeSerialize<Animal>(filename);
return str;
}
private void mnuFileOpen_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
string thefilename = openFileDialog1.FileName;
Animal msg = ReadFile(thefilename);
if (msg != null)
{
Resultlst.Items.Add(msg);
}
else
UpdateResults();
}
}
I'm not getting any error. The problem is that it opens and display only the first object in the file. I want it to open and display all the objects in that file.
UPDATE:
This is how I Serialized it:
public void BinaryFileSerialize(object[] objs, string filePath)
{
FileStream fileStream = null;
try
{
fileStream = new FileStream(filePath, FileMode.Create);
BinaryFormatter b = new BinaryFormatter();
foreach (var obj in objs)
{
b.Serialize(fileStream, obj);
}
}
catch
{
throw;
}
finally
{
if (fileStream != null)
fileStream.Close();
}
}
UPDATE 2:
public T BinaryFileDeSerialize<T>(string filePath)
{
FileStream fileStream = null;
Object obj;
if (!File.Exists(filePath))
throw new FileNotFoundException("The file" + " was not found. ", filePath);
using (var thefileStream = new FileStream(filePath, FileMode.Open))
{
BinaryFormatter b = new BinaryFormatter();
obj = b.Deserialize(thefileStream);
}
return (T)obj;
}
private Animal[] ReadFile(string filename)
{
BinSerializerUtility BinSerial = new BinSerializerUtility();
var animals = BinSerial.BinaryFileDeSerialize<Animal[]>(filename);
return animals;
}
private void mnuFileOpen_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
string thefilename = openFileDialog1.FileName;
Animal []msg = ReadFile(thefilename);
if (msg != null)
{
Resultlst.Items.Add(msg);
}
else
UpdateResults();
}
I'm getting error:
Failed to convert an object of type Namespace.Animal to type
System.Collections.Generic.List`1 [Namespace.Animal].
The error comes from this return (T)obj;
If you want to use the current serializer you should change deserialize methos as follow:
public IList<T> BinaryFileDeSerialize<T>(string filePath) where T: class
{
var list = new List<T>();
if (!File.Exists(filePath))
throw new FileNotFoundException("The file" + " was not found. ", filePath);
using(var fileStream = new FileStream(filePath, FileMode.Open))
{
BinaryFormatter b = new BinaryFormatter();
while(fileStream.Position < fileStream.Length)
list.Add((T)b.Deserialize(fileStream));
}
return list;
}
And ReadFile should be like this:
private Animal[] ReadFile(string filename)
{
BinSerializerUtility BinSerial = new BinSerializerUtility();
var animals = BinSerial.BinaryFileDeSerialize<Animal>(filename);
return animals.ToArray();
}
private void mnuFileOpen_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
string thefilename = openFileDialog1.FileName;
var messages = ReadFile(thefilename);
if (messages != null)
{
messages.ToList().ForEach(msg =>
Resultlst.Items.Add(msg));
}
else
{
UpdateResults();
}
}
}
Silly question, but what happens if you serialize as List<Animal> then try to call BinaryFileDeSerialize<List<Animal>>()?
Also, you can simplify your method thusly with a using statement.
public T BinaryFileDeSerialize<T>(string filePath)
{
FileStream fileStream = null;
Object obj;
if (!File.Exists(filePath))
throw new FileNotFoundException("The file" + " was not found. ", filePath);
using(var fileStream = new FileStream(filePath, FileMode.Open))
{
BinaryFormatter b = new BinaryFormatter();
obj = b.Deserialize(fileStream);
}
return (T)obj;
}
EDIT:
Try these tweaks to your code...
//call via BinaryFileSerialize<Animal>(..., ...);
public void BinaryFileSerialize<T>(T[] objs, string filePath)
{
using(var fileStream = new FileStream(filePath, FileMode.Create))
{
BinaryFormatter b = new BinaryFormatter();
b.Serialize(fileStream, objs);
}
}
private Animal[] ReadFile(string filename)
{
BinSerializerUtility BinSerial = new BinSerializerUtility();
var animals = BinSerial.BinaryFileDeSerialize<Animal[]>(filename);
return animals;
}

Reading serialized objects from binary file

I'm trying to write and read serialized objects to a binary file. I'm using Append FileMode to add serialized objects but when i try to read the file, it only print a single deserialized object.
Here's my serialization method.
public void serialize(){
MyObject obj = new MyObject();
obj.n1 = 1;
obj.n2 = 24;
obj.str = "Some String";
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream("MyFile.bin", FileMode.Append, FileAccess.Write, FileShare.None);
formatter.Serialize(stream, obj);
stream.Close()
}
Here's my deserialization method.
public static void read()
{
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream("MyFile.bin", FileMode.Open, FileAccess.Read, FileShare.Read);
MyObject obj = (MyObject)formatter.Deserialize(stream);
stream.Close();
// Here's the proof.
Console.WriteLine("n1: {0}", obj.n1);
Console.WriteLine("n2: {0}", obj.n2);
Console.WriteLine("str: {0}", obj.str);
}
How can we loop through every single serialized record in file, like we use File.eof() or while(file.read()) in C++.
Deserialize only returns one object. You need to create a collection and loop until the end of the stream is reached:
List<MyObject> list = new List<MyObject>();
Stream stream = new FileStream("MyFile.bin", FileMode.Open, FileAccess.Read, FileShare.Read);
while(stream.Position < stream.Length)
{
MyObject obj = (MyObject)formatter.Deserialize(stream);
list.add(obj);
}
The explanation above is correct, however I'd put it like this, using a collection of your like:
public static void serializeIt()
{
MyObject obj = new MyObject();
obj.n1 = 1;
obj.n2 = 24;
obj.str = "Some String";
MyObject obj2 = new MyObject();
obj2.n1 = 1;
obj2.n2 = 24;
obj2.str = "Some other String";
List<MyObject> list = new List<MyObject>();
list.Add(obj);
list.Add(obj2);
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream("MyFile.bin", FileMode.Append,FileAccess.Write, FileShare.None);
formatter.Serialize(stream, list);
stream.Close();
}
public static void read()
{
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream("MyFile.bin", FileMode.Open, FileAccess.Read, FileShare.Read);
List<MyObject> list = (List<MyObject>)formatter.Deserialize(stream);
stream.Close();
}
You should also make sure that the MyFile.bin is rewriten each time you serialize your collection, as it would always return the collection that was saved first if you'd keep appending them. That should be the only downside.
Thank you for your help, I made this.
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
private static Dictionary<int, ArrayList> J1_CarteDeck;
private static string PathDocuments = String.Format("{0}\\Antize Game\\", Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments));
private const string FILE_NAME = "Antize.data";
public static bool SauvegarderDeck()
{
if (!(Directory.Exists(PathDocuments)))
Directory.CreateDirectory(PathDocuments);
if (File.Exists(PathDocuments + FILE_Deck))
File.Delete(PathDocuments + FILE_Deck);
foreach (ArrayList child in J1_CarteDeck.Values)
{
if(child != null)
{
BinaryFormatter formatter = new BinaryFormatter();
FileStream stream = new FileStream(PathDocuments + FILE_Deck, FileMode.Append, FileAccess.Write, FileShare.None);
formatter.Serialize(stream, child);
stream.Close();
}
}
if (File.Exists(PathDocuments + FILE_Deck))
return true;
else
return false;
}
public static bool ChargerDeck()
{
if (!(File.Exists(PathDocuments + FILE_Deck)))
return false;
int cptr = 1;
J1_CarteDeck = new Dictionary<int, ArrayList>();
BinaryFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream(PathDocuments + FILE_Deck, FileMode.Open, FileAccess.Read, FileShare.None);
while (stream.Position < stream.Length)
{
J1_CarteDeck[cptr] = (ArrayList)formatter.Deserialize(stream);
cptr++;
}
stream.Close();
return true;
}
Simply iterate through each object in binary file
using (System.IO.FileStream fs = new System.IO.FileStream("D:\\text\\studentdata.txt", System.IO.FileMode.Open, System.IO.FileAccess.Read))
{
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter sf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
Object o = sf.Deserialize(fs);
while (fs.Position < fs.Length)
{
o = sf.Deserialize(fs);
Student student = (o as Student);
Console.WriteLine("str: {0}", student.sname);
}
}

How do I zip files in Xamarin for Android?

I have a function that creates a zip file a string array of files passed. The function does succeed in creating the zip file and the zip entry files inside it, but these zip entry files are empty. I've tried a couple of different methods - the function code below is the closest I've gotten to something working:
public static bool ZipFile(string[] arrFiles, string sZipToDirectory, string sZipFileName)
{
if (Directory.Exists(sZipToDirectory))
{
FileStream fNewZipFileStream;
ZipOutputStream zos;
try {
fNewZipFileStream = File.Create(sZipToDirectory + sZipFileName);
zos = new ZipOutputStream(fNewZipFileStream);
for (int i = 0; i < arrFiles.Length; i++) {
ZipEntry entry = new ZipEntry(arrFiles[i].Substring(arrFiles[i].LastIndexOf("/") + 1));
zos.PutNextEntry(entry);
FileStream fStream = File.OpenRead(arrFiles[i]);
BufferedStream bfStrm = new BufferedStream(fStream);
byte[] buffer = new byte[bfStrm.Length];
int count;
while ((count = bfStrm.Read(buffer, 0, 1024)) != -1) {
zos.Write(buffer);
}
bfStrm.Close();
fStream.Close();
zos.CloseEntry();
}
zos.Close();
fNewZipFileStream.Close();
return true;
}
catch (Exception ex)
{
string sErr = ex.Message;
return false;
}
finally
{
fNewZipFileStream = null;
zos = null;
}
}
else
{
return false;
}
}
I think it's got to do with the byte stream handling. I've tried this bit of code that handles the stream but it goes into an infinite loop:
while ((count = fStream.Read(buffer, 0, 1024)) != -1) {
zos.Write(buffer, 0, count);
}
fStream.Close();
I found a solution that is quite simple - I used the ReadAllBytes method of the static File class.
ZipEntry entry = new ZipEntry(arrFiles[i].Substring(arrFiles[i].LastIndexOf("/") + 1));
zos.PutNextEntry(entry);
byte[] fileContents = File.ReadAllBytes(arrFiles[i]);
zos.Write(fileContents);
zos.CloseEntry();
Using Read() on a FileStream returns the amount of bytes read into the stream or 0 if the end of the stream has been reached. It will never return a value of -1.
From MSDN:
The total number of bytes read into the buffer. This might be less than the number of bytes requested if that number of bytes are not currently available, orzero if the end of the stream is reached.
I'd modify your code to the following:
System.IO.FileStream fos = new System.IO.FileStream(sZipToDirectory + sZipFileName, FileMode.Create);
Java.Util.Zip.ZipOutputStream zos = new Java.Util.Zip.ZipOutputStream(fos);
byte[] buffer = new byte[1024];
for (int i = 0; i < arrFiles.Length; i++) {
FileInfo fi = new FileInfo (arrFiles[i]);
Java.IO.FileInputStream fis = new Java.IO.FileInputStream(fi.FullName);
ZipEntry entry = new ZipEntry(arrFiles[i].Substring(arrFiles[i].LastIndexOf("/") + 1));
zos.PutNextEntry(entry);
int count = 0;
while ((count = fis.Read(buffer)) > 0) {
zos.Write(buffer, 0, count);
}
fis.Close();
zos.CloseEntry();
}
This is nearly identical to the code I've used for creating zip archives on Android in the past.
Are you allowed to use SharpZip? It's really easy to use.
Here is a blog post I wrote to extract zip files
private static void upzip(string url)
{
WebClient wc = new WebClient();
wc.DownloadFile(url, "temp.zip");
//unzip
ZipFile zf = null;
try
{
zf = new ZipFile(File.OpenRead("temp.zip"));
foreach (ZipEntry zipEntry in zf)
{
string fileName = zipEntry.Name;
byte[] buffer = new byte[4096];
Stream zipStream = zf.GetInputStream(zipEntry);
using (FileStream streamWriter = File.Create( fileName))
{
StreamUtils.Copy(zipStream, streamWriter, buffer);
}
}
}
finally
{
if (zf != null)
{
zf.IsStreamOwner = true;
zf.Close();
}
}
}
private void ZipFolder(string[] _files, string zipFileName)
{
using var memoryStream = new MemoryStream();
using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
{
foreach (var item in _files)
{
var demoFile = archive.CreateEntry(Path.GetFileName(item));
using var readStreamW = File.OpenRead(item);
using (var entryStream = demoFile.Open())
{
using (var streamWriter = new StreamWriter(entryStream))
{
readStreamW.Seek(0, SeekOrigin.Begin);
readStreamW.CopyTo(streamWriter.BaseStream);
}
}
}
}
using var fileStream = new FileStream(zipFileName, FileMode.Create);
memoryStream.Seek(0, SeekOrigin.Begin);
memoryStream.CopyTo(fileStream);
}

"Binary stream does not contain a valid BinaryHeader" error on (de)serialization?

I am created a post before " Object to byte not working " .
I fixed problems that users said me , but there is still problem .
Error Message : The constructor to deserialize an object of type 'WindowsFormsApplication1.Form1+Item' was not found.;
void start()
{
Item item = new Item();
item.files.Add(#"test");
byte[] b = ObjectToByteArray(item);
Item k = Desriles(b);
}
[Serializable]
public class Item : ISerializable
{
public Item()
{
files = new List<string>();
Exclude = false;
CleanEmptyFolder = false;
}
public List<string> files;
public string MusicProfileName;
public bool Exclude;
#region ISerializable Members
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("files", files);
info.AddValue("MusicProfileName", MusicProfileName);
info.AddValue("Exclude", Exclude);
}
#endregion
}
public byte[] ObjectToByteArray(object _Object)
{
using (var stream = new MemoryStream())
{
// serialize object
var formatter = new BinaryFormatter();
formatter.Serialize(stream, _Object);
// get a byte array
var bytes = new byte[stream.Length];
using (BinaryReader br = new BinaryReader(stream))
{
bytes = br.ReadBytes(Convert.ToInt32(stream.Length));
}
return bytes;
}
}
public Item Desriles(byte[] items)
{
using (MemoryStream stream = new MemoryStream())
{
stream.SetLength(items.LongLength);
stream.write(items, 0, items.Length);
var formatter = new BinaryFormatter();
stream.Seek(0, SeekOrigin.Begin);
object item = formatter.Deserialize(stream); // Here I will get error
return (Item)item;
}
}
The serialization code can't work properly, you forgot to reset the stream back to the beginning. The better mouse trap:
public byte[] ObjectToByteArray(object _Object) {
using (var stream = new MemoryStream()) {
var formatter = new BinaryFormatter();
formatter.Serialize(stream, _Object);
return stream.ToArray();
}
}
The deserialization code can similarly be simplified:
public Item Desriles(byte[] items) {
using (MemoryStream stream = new MemoryStream(items)) {
var formatter = new BinaryFormatter();
return (Item)formatter.Deserialize(stream);
}
}
And you don't need GetObjectData().
In this section:
using (MemoryStream stream = new MemoryStream())
{
stream.SetLength(items.LongLength);
stream.Read(items, 0, items.Length);
[...]
object item = formatter.Deserialize(stream);
it seems you are creating a new, empty memory stream, then attempting to read from it, and Deserialize from it.
Of course it fails. The stream is empty.
abelenky makes a good point, but I don't think your:
public byte[] ObjectToByteArray(object _Object)
works either.
C# Code Snippet - Object to byte array
C# Code Snippet - Byte array to object
Thanks to All :
I found problem : I should base that to ISerializable

How to keep XmlSerializer from killing NewLines in Strings?

Suppose I have a simple Class with just one Member a String.
public class Abc
{
private String text;
public String Text
{
get { return this.text; }
set { this.text = value; }
}
}
Now when I serialize and then deserialize it with the questionable XmlSerializer any text containing newlines ('\r\n' or Environment.NewLine) are transformed to '\n'.
How do I keep the newlines?
It is not the XmlSerializer but the XmlWriter which is removing your CR. To retain it we must have the writer convert CR to its character entity 
.
XmlWriterSettings ws = new XmlWriterSettings();
ws.NewLineHandling = NewLineHandling.Entitize;
XmlSerializer ser = new XmlSerializer( typeof( Abc ) );
using (XmlWriter wr = XmlWriter.Create( "abc.xml", ws )) {
ser.Serialize( wr, s );
}
This is exactly the same with DataContractSerializer:
var ser = new DataContractSerializer( typeof( Abc ) );
using (XmlWriter wr = XmlWriter.Create( "abc.xml", ws )) {
ser.Serialize( wr, s );
}
Why do we need to do this?
This is because compliant XML parsers must, before parsing, translate CRLF and any CR not followed by a LF to a single LF. This behavior is defined in the End-of-Line handling section of the XML 1.0 specification.
As this happens before parsing, you need to encode CR as its character entity if you want the CR to exist in the document.
public class SerializeAny<TF> where TF : new()
{
public static TF Deserialize(string serializedData)
{
try
{
var xmlSerializer = new XmlSerializer(typeof(TF));
TF collection;
using (var xmlReader = new XmlTextReader(serializedData, XmlNodeType.Document, null))
{
collection = (TF)xmlSerializer.Deserialize(xmlReader);
}
return collection;
}
catch (Exception)
{
}
return new TF();
}
public static TF DeserializeZip(string path)
{
try
{
var bytes = File.ReadAllBytes(path);
string serializedData = Unzip(bytes);
TF collection = Deserialize(serializedData);
return collection;
}
catch (Exception)
{
}
return new TF();
}
public static string Serialize(TF options)
{
var xml = "";
try
{
var xmlSerializer = new XmlSerializer(typeof(TF));
using (var stringWriter = new StringWriter())
{
xmlSerializer.Serialize(stringWriter, options);
xml = stringWriter.ToString();
}
}
catch (Exception ex)
{
return ex.Message;
}
return xml;
}
public static string SerializeZip(TF options, string path)
{
var xml = "";
try
{
xml = Serialize(options);
var zip = Zip(xml);
File.WriteAllBytes(path, zip);
}
catch (Exception ex)
{
return ex.Message;
}
return xml;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times")]
internal static String SerializeObject<T>(T obj, Encoding enc)
{
using (var ms = new MemoryStream())
{
var xmlWriterSettings = new System.Xml.XmlWriterSettings()
{
// If set to true XmlWriter would close MemoryStream automatically and using would then do double dispose
// Code analysis does not understand that. That's why there is a suppress message.
CloseOutput = false,
Encoding = enc,
OmitXmlDeclaration = false,
Indent = true
};
using (var xw = XmlWriter.Create(ms, xmlWriterSettings))
{
var s = new XmlSerializer(typeof(T));
s.Serialize(xw, obj);
}
return enc.GetString(ms.ToArray());
}
}
private static void CopyTo(Stream src, Stream dest)
{
byte[] bytes = new byte[4096];
int cnt;
while ((cnt = src.Read(bytes, 0, bytes.Length)) != 0)
{
dest.Write(bytes, 0, cnt);
}
}
private static byte[] Zip(string str)
{
var bytes = Encoding.UTF8.GetBytes(str);
using (var msi = new MemoryStream(bytes))
using (var mso = new MemoryStream())
{
using (var gs = new GZipStream(mso, CompressionMode.Compress))
{
//msi.CopyTo(gs);
CopyTo(msi, gs);
}
return mso.ToArray();
}
}
private static string Unzip(byte[] bytes)
{
using (var msi = new MemoryStream(bytes))
using (var mso = new MemoryStream())
{
using (var gs = new GZipStream(msi, CompressionMode.Decompress))
{
CopyTo(gs, mso);
}
return Encoding.UTF8.GetString(mso.ToArray());
}
}
}
public class BinarySerialize<T> where T : new()
{
public static string Serialize(T options, string path)
{
var xml = "";
try
{
File.Delete(path);
}
catch (Exception)
{
}
try
{
using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.ReadWrite))
{
var bf = new BinaryFormatter();
bf.Serialize(fs, options);
}
}
catch (Exception ex)
{
return ex.Message;
}
return xml;
}
public static T Deserialize(string path)
{
T filteroptions;
using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))
{
var bf = new BinaryFormatter();
filteroptions = (T)bf.Deserialize(fs);
}
return filteroptions;
}
}
Use this code:
public static FilterOptions Deserialize(string serializedData)
{
try
{
var xmlSerializer = new XmlSerializer(typeof(FilterOptions));
var xmlReader = new XmlTextReader(serializedData,XmlNodeType.Document,null);
var collection = (FilterOptions)xmlSerializer.Deserialize(xmlReader);
return collection;
}
catch (Exception)
{
}
return new FilterOptions();
}
Nice solution, Lachlan Roche!
The function below (in VB.NET) uses a StringWriter to return a String, rather than writing the result to a file using an XmlWriter.
''' <summary>
''' Exports the object data to an XML formatted string.
''' Maintains CR characters after deserialization.
''' The object must be serializable to work.
''' </summary>
Public Function ExportObjectXml(ByVal obj As Object) As String
If obj Is Nothing Then
Return String.Empty
End If
Dim serializer As New XmlSerializer(obj.GetType)
Dim settings As New XmlWriterSettings With {.NewLineHandling = NewLineHandling.Entitize}
Using output As New StringWriter
Using writer As XmlWriter = XmlWriter.Create(output, settings)
serializer.Serialize(writer, obj)
Return output.ToString
End Using
End Using
End Function

Categories

Resources