I need to read several lists of 2D coordinates into a data collection, like a Dictionary for example, from a text file.
I can make the file into any format (it´s originally an SVG but I made an ETL that cleans it and can spit JSON or whatever other format) but JSON is preferred.
Thanks!
Well, I do it using FileStream. I first save the length of the array and then do a for loop to save the data.
Here is an example of saving an array on integers in C#
`
using System.IO;
public class SomeClass
{
FileStream file;
public void SaveArray(int[] arr)
{
file = File.open("myfile.format", FileMode.OpenOrCreate);
byte[] arraySize = System.BitConverter.GetBytes(arr.Length);
file.Write(arraySize, 0, sizeof(int));
for(int i = 0; i < arr.Length; i++)
{
byte[] arrayElement = System.BitConverter.GetBytes(arr*);*
-
file.Write(arrayElement, 0, sizeof(int));*
-
}*
-
file.Close();*
-
}*
-
public void LoadArray(int[] arr)*
-
{*
-
if (file = File.Open("myfile.format", FileMode.Open))*
-
{*
-
byte[] arraySize = new byte[sizeof(int)];*
-
file.Read(arraySize, 0, sizeof(int));*
-
arr = new int[arraySize];*
-
for (int i = 0; i < arraySize; i++)*
-
{*
-
byte[] arrayElement = new byte[sizeof(int)];*
-
file.Read(arrayElement, 0, sizeof(int));*
_ arr = System.BitConverter.ToInt32(arrayElement);_
* }*
* file.Close();*
* }*
* }*
* }*
*_ _*You need to remember, when saving, things come out in the exact same way they go in.*_ _*So since you are doing an array of 2D coordinates. That means in the loop, you would do 2 writes and 2 reads instead of one. One for each float in the coordinate.*_ _*
for(int i = 0; i < arr.Length; i++)
{
byte[] arrayElement = System.BitConverter.GetBytes(arr*.x);*
file.Write(arrayElement, 0, sizeof(int));
arrayElement = System.BitConverter.GetBytes(arr*.y);*
file.Write(arrayElement, 0, sizeof(int));
}
`
The same principles should apply with whatever format you choose to use. You just need to find out how the co-ordinates are stored in the file so you know what datatypes to pull out the data as.
© 2022 - 2024 — McMap. All rights reserved.
Thanks for the extensive reply. This is for binary files, but I'd like to interpret text files in a format like JSON for example. And I made a mistake, I wrote arrays, but I was thinking rather in a more flexible data collection like Dictionaries.
– OvidaWhat does the data look like in the file
– AirtightIt could be any format, but I prefer JSON.
– Ovida