C # splits text file into two dimensional array of strings
I have a text file that looks like this:
John,Gauthier,blue,May Henry,Ford,Red,June James,Bond,Orange,December
I want to split it into a 2 dimensional array of strings so that I can split each string and then all the words. Example:
mystring[0][0] = "John"
mystring[1][3] = "June"
mystring[2][2] = "Orange"
Here's what I did right now:
string[] words = new string [100];
System.IO.StreamReader myfile = new System.IO.StreamReader("c:\\myfile.csv");
while (fichier.Peek() != -1)
{
i++;
words = myfile.ReadLine().Split(',');
}
I am stuck. I can split it into a one dimensional string array, but not a two dimensional string array. I guess I need to split it two times; First time with '\ n' and second time with ',', and then put the two together.
source to share
It's actually a one-liner:
File.ReadLines("myfilename.txt").Select(s=>s.Split(',')).ToArray()
Since this is a beginner's question, here's what happens:
File.ReadLines (filename) returns a collection of all lines in your text file
.Choose an extension method that accepts a function
s => s.Split (',') is a function, it splits the string s into all commas and returns an array of strings.
.ToArray () takes a collection of string arrays created with .Select and makes an array out of that, so you end up with an array of arrays.
source to share
Try:
var First = new string [100];
var Sec = new string [100];
System.IO.StreamReader myfile = new System.IO.StreamReader("c:\\myfile.csv");
while (fichier.Peek() != -1)
{
i++;
var buff = myfile.ReadLine().Split(',');
First[i] = buff[0];
Sec[i] = buff[1];
}
Another idea, use an XML serializer to serialize your object. Two extensions for this:
public static void SaveAsXML(this Object A, string FileName)
{
var serializer = new XmlSerializer(A.GetType());
using (var textWriter = new StreamWriter(FileName))
{
serializer.Serialize(textWriter, A);
textWriter.Close();
}
}
public static void LoadFromXML(this Object A, string FileName)
{
if (File.Exists(FileName))
{
using (TextReader textReader = new StreamReader(FileName))
{
XmlSerializer deserializer = new XmlSerializer(A.GetType());
A = (deserializer.Deserialize(textReader));
}
}
}
Add than in any Static class and call:
YourSaveClassWhitchContainsYourArray.SaveAsXML("Datastore.xml");
or
YourSaveClassWhitchContainsYourArray.LoadFromXML("Datastore.xml");
source to share