Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serializing Arrays in C#

Is there a way to Serialize an entire array in C# such as:

[Serializable()]
public class Data
{
    public short Some_Short_Data = new short[100,100];
    public string Some_String_Data = new string[100,100];
}

Then writting the file:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


using System.Xml;
using System.Xml.Serialization;
using System.IO;

Data Write_Data = new Data();

XmlSerializer Writer = new XmlSerializer(typeof(Data));

    using (FileStream file = File.OpenWrite("Myfile.xml"))
    {
        Writer.Serialize(file, Write_Data); //Writes data to the file
    }

When I try this, it fails on: XmlSerializer Writer = new XmlSerializer(typeof(Data));

Saying: "There was an error reflecting type 'Data' "

I am particularly new to both Stack and Xml/Xml Serialization so any help would be appreciated.

like image 274
Ewan Avatar asked Mar 25 '23 03:03

Ewan


2 Answers

Multi-dimensional arrays are not supported by XmlSerialzier. But you can make a workaround by using a temp class something like this

public class Array100<T>
{
    public T[] Data = new T[100];
}

public class Data
{
    public Array100<short>[] Some_Short_Data = new Array100<short>[100];
    public Array100<string>[] Some_String_Data = new Array100<string>[100];
}

BTW: No need for Serializable attribute. It is not used by XmlSerialzier

like image 93
I4V Avatar answered Mar 26 '23 18:03

I4V


You cannot serialze a int[,] but you can serialize a int[][]. Before serializing your 2D array, just convert it into a jagged array like that :

var my2dArray = new int[2,5];
var myJaggedArray = new int [2][];

for(int i = 0 ; i < my2DArray.GetLength(0) ; i ++)
{
    myJaggedArray[i] = new int[my2DArray.GetLength(1)];

    for(int j = 0 ; j < my2DArray.GetLength(1) ; j ++)
        myJaggedArray[i][j] = my2DArray[i,j]; 
}
like image 41
qdruault Avatar answered Mar 26 '23 16:03

qdruault