简体   繁体   中英

C# export / write multidimension array to file (csv or whatever)

Hi Designing a program and i just wanted advise on writing a multiDim array to a file. I am using XNA and have a multidimension array with a Vector3(x, y, z)'s in it.

There are hundred thousand if not millions of values, and i want to be able to save them in a file (saving the game level). I have no bias to one idea, i just need to store data...thats it! All the other game data like player stats etc etc i am using XMLSerializer and its working wonders.

Now i was playing with xml serializer alot and have learn that you cannot export MultiDim Arrays... so frustrating (but i am sure there is a good reason why - hopefully). I played with Jagged's with no luck.

Used System.IO.File.WriteAllText then quickly relised that is only for string... daahhh

Basically i think i need to go down the BinaryWrite method, re-writing my own serializer, over even try running a sql server to host the masses of data... stupid idea? please tell me and can you point me in the write direction. As i primarily have a web (php) background the thought of running a server that syncs data / level data is attractive to me... but might not be applicable here.

Thanks for anything,

Mal

You can just serialise the lot with the built-in .NET serialisers provided the objects in the array are serialisable (and IIRC Vector3s are).

void SerializeVector3Array(string filename, Vector3[,] array)
{
    BinaryFormatter bf = new BinaryFormatter();
    Stream s = File.Open(filename, FileMode.Create);
    bf.Serialize(s, array);
    s.Close();
}

Vector3[,] DeserializeVector3Array(string filename)
{
    Stream s = File.Open(filename, FileMode.Open);
    BinaryFormatter bf = new BinaryFormatter();
    Vector3[,] array = (Vector3[,])bf.Deserialize(s);
    s.Close();
    return array;
}

That should be a rough template of what you're after.

Why dont you try Json Serialization? Json has less noise than XML, occupies less space when written to file especially if you do so without indenting, etc. It does not have trouble with arrays, dictionaries, dates and other objects as far as my experience with it goes.

I recommend using JSON.NET and if not, then look at this thread

If Json.net finds it difficult to serialize a library class with many private & static variables, then it is trivial to write a POCO class and map the library class essential properties to your POCO and serialize and map the POCO back and forth.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM