86275

C# split textfile into a 2 dimensional string array

Question:

I have a textfile that looks like this :

John,Gauthier,blue,May Henry,Ford,Red,June James,Bond,Orange,December

I want to split it into a two dimensional string array so I could separate each lines then each words. Ex:

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'm stuck. I'm able to split it into a one dimensional string array but not into a two dimensional string array. I guess I need to split it two times ; First time with '\n' and the second time with ',' and then put those two together.

Answer1:

This is actually a one-liner:

File.ReadLines("myfilename.txt").Select(s=>s.Split(',')).ToArray()

Since this is a beginner question, here's what's going on:

File.ReadLines(filename) returns a collection of all lines in your text file

.Select is an extension method that takes a function

s=>s.Split(',') is the function, it splits the string s by all commas and returns an array of strings.

.ToArray() takes the collection of string arrays created by .Select and makes an array out of that, so you get array of arrays.

Answer2:

Try this

var str = File.ReadAllText("myfile.csv"); var arr = str.Split(new string[] {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries); var multi = arr.Select(x => x.Split(',')).ToArray();

Answer3:

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]; }

Other idea, use a XML serilizer to serilize your hole 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");

Recommend

  • Read specific string from each line of text file using BufferedReader in java
  • Deserialize Json.net JSON File directly to a C# dictionary type?
  • How to create packages (folders) in an Eclipse project via plugin
  • Convert different encodings to ascii
  • Why can I create an instance of a class without storing it to a variable and still have everything w
  • HikariCP hanging on getConnection
  • How to use fmt.Sscan to parse integers into an array?
  • Compressing “n”-time object member call
  • Add to stack from ArrayList (Java)
  • Peek MSMQ message with infinite timeout
  • Extracting words from txt file using python
  • Python : Finding an item in a list where a function return a minimum value?
  • How to make a variable by extracting specific line?
  • How to read data from socket connection - android
  • StreamWriter won't flush to NetworkStream
  • Convert data type in R or Python
  • C# where to add a method
  • vi mode to emacs mode while on R
  • Encode string to match encoded form field name in PHP POST array
  • Python: Split a String Field into 3 Separate Fields using Lambda
  • how can I compare dates in array to find the earliest one?
  • Divide a $1 by 3 and adjusting 1 cent
  • How do I shift the decimal place in Python?
  • Reading a file into a multidimensional array
  • Atlas images wrong size on iPad iOS 9
  • Java: can you cast Class into a specific interface?
  • NetLogo BehaviorSpace - Measure runs using reporters
  • AES padding and writing the ciphertext to a disk file
  • Updating server-side rendering client-side
  • Does CUDA 5 support STL or THRUST inside the device code?
  • How to extract text from Word files using C#?
  • ActionScript 2 vs ActionScript 3 performance
  • Run Powershell script from inside other Powershell script with dynamic redirection to file
  • Load html files in TinyMce
  • How can I get HTML syntax highlighting in my editor for CakePHP?
  • coudnt use logback because of log4j
  • Can Visual Studio XAML designer handle font family names with spaces as a resource?
  • How can I remove ASP.NET Designer.cs files?
  • Are Kotlin's Float, Int etc optimised to built-in types in the JVM? [duplicate]
  • java string with new operator and a literal