C# StreamReader save to Array with separator - c#

I´ve got a text file with tabulator separated data. What I need in my C# application is that I read one line from the text file and save them to an array, separate them at the each \t. Then I do the same thing with the next row.
My code:
StreamReader sr = new StreamReader(dlg.FileName);
string s = sr.ReadLine();
Now, I already tried to write the line into an array but that doesn´t work. Does anyone one how to manage this?

Use the Split method to create an Array of the line
string[] parts = s.Split('\t');
See Documentation on Split() here

foreach (string line in System.IO.File.ReadAllLines(dlg.FileName))
{
var myArray = line.Split('\t');
}

s.Split('\t') will split your string by the tabulator character, and create a string[] with appropriate length.

Ammending your example code:
StreamReader sr = new StreamReader(dlg.FileName);
string s = sr.ReadLine();
var items = s.Split('\t');
In the end, items contains an array of strings that represent the characters between the tabs. The tabs are not included in the array. The array may contain empty elements (for the case of two consecutive tabs).

Use the String.Split() method: http://msdn.microsoft.com/en-us/library/b873y76a.aspx

StreamReader reader = new StreamReader("input.txt");
string[] content = reader.ReadToEnd().Replace("\n","").Split('\t');
if you want to keep New Line's than
string[] content = reader.ReadToEnd().Split('\t');

In the example below, items will be a String[] containing each line of text's values. It will be overwritten with each iteration so you'll want to do something with it inside the loop. Save it to a larger collection, write it to a file, etc...
StreamReader sr = new StreamReader(dlg.FileName);
while (sr.Peek() >= 0) {
var line = sr.ReadLine();
var items = line.Split(new Char[] { '\t' });
}

If the file contains only one line, then use:
string[] myArray = s.Split('\t');

Related

How can I extract the first word of every line of a text file in C#

Currently trying to read the first word of every line
while ((line = studentsReader.ReadLine()) != null)
{
foreach (var lines in line.Split('\n'))
{
arr = line.Split(',');
}
}
Tried that but it doesn't work, arr[1] still gives me the name Oliver
I want arr[0] to be v12345 and arr[1] to be v54321 not Oliver
The text file looks something like this:
v12345, Oliver, Queen
v54321, Barry, Allen
v51213, Tony, Stark
You need to add the first word to a new collection.
var arr = new List<string>();
while ((line = studentsReader.ReadLine()) != null)
{
arr.Add(line.Split(',')[0]);
}
if this is a file then you can do
var arr = File.ReadLines(<file name>).Select(l=>l.Split(',')[0]).ToList();
Sorry. but your code is a mess.
while ((line = studentsReader.ReadLine()) != null)//ReadLine reads only one line from a file, e. g. v12345, Oliver, Queen
{
foreach (var lines in line.Split('\n'))//spiltting than single line by '\n' does nothing
{
/*Now you split by ',' not the iterator, which is lines,
but an original string, which is line.
But because you didn't actually split anything it makes no difference*/
arr = line.Split(',');
/*here you've got an array of strings {v12345, Oliver, Queen}
On next iteration you'll read another line from a file and
get the same array from another string, etc. And on each iteration
the arr will be a new array, so after the last iteration you'll get
the last line of file*/
}
}
You should do something like this
List<string> firstWords = new List<string>();
while(line = studentsReader.ReadLine()!=null)
{
firstWords.Add(line.Split(',')[0]);
}
the array index is zero based. so arr[0] will give you the first word.

Got wrong data while split file into arrays

I have file contains two lines and each line contains 200 fields and I would like to split it into arrays
using (StreamReader sr = File.OpenText(pathSensorsCalc))
{
string s = String.Empty;
while ((s = sr.ReadLine()) == null) { };
String line1 = sr.ReadToEnd();
String line2 = sr.ReadToEnd();
CalcValue[0] = new String[200];
CalcValue[1] = new String[200];
CalcValue[0] = line1.Split(' ');
CalcValue[1] = line2.Split(' ');
}
After the code above, CalcValue[1] is empty and CalcValue[0] contains data of the second line (instad of the first one). Any ideas?
When using
sr.ReadToEnd()
, you are reading to the end of your input stream. That means, after the first call of
String line1 = sr.ReadToEnd()
your stream is already at the last position. Replace your ReadToEnd() call with ReadLine() calls. That should work.
In the Windows OS, a new line is represented by \r\n. So you should not split the lines by spaces (" ").
Which means you should use another overload of the Split method - Split(char[], StringSplitOptions). The first argument is the characters you want to split by and the second is the options. Why do you need the options? Because if you split by 2 continuous characters you get an empty element.
So now it is easy to understand what this code does and why:
line1.Split (new[] {'\r', '\n'}, StringSplitOptions.RemoveEmptyEntries);

read only given last x lines in txt file [duplicate]

This question already has answers here:
Get last 10 lines of very large text file > 10GB
(21 answers)
Closed 9 years ago.
Currently I'm reading file content using File.ReadAllText(), but now I need to read last x lines in my txt file. How can I do that?
content of myfile.txt
line1content
line2content
line3content
line4content
string contentOfLastTwoLines = ...
What about this
List <string> text = File.ReadLines("file.txt").Reverse().Take(2).ToList()
Use Queue<string> to store last X lines and replace the first one with currently read:
int x = 4; // number of lines you want to get
var buffor = new Queue<string>(x);
var file = new StreamReader("Input.txt");
while (!file.EndOfStream)
{
string line = file.ReadLine();
if (buffor.Count >= x)
buffor.Dequeue();
buffor.Enqueue(line);
}
string[] lastLines = buffor.ToArray();
string contentOfLastLines = String.Join(Environment.NewLine, lastLines);
You can use ReadLines to avoid reading the entire file into memory, like this:
const int neededLines = 5;
var lines = new List<String>();
foreach (var s in File.ReadLines("c:\\myfile.txt")) {
lines.Add(s);
if (lines.Count > neededLines) {
lines.RemoveAt(0);
}
}
Once the for loop is finished, the lines list contains up to the last neededLines of text from the file. Of course if the file does not contain as many lines as required, fewer lines will be placed in the lines list.
Read the lines into an array, then extract the last two:
string[] lines = File.ReadAllLines();
string last2 = lines[lines.Count-2] + Environment.NewLine + lines[lines.Count-1];
Assuming your file is reasonably small, it's easier to just read the whole thing and throw away what you don't need.
Since reading a file is done linearly, usually line-by-line. Simply read line-by-line and remember last two lines (you can use queue or something if you want... or just two string variables). When you get to EOF, you'll have your last two lines.
You want to read the file backwards using ReverseLineReader:
How to read a text file reversely with iterator in C#
Then run .Take(2) on it.
var lines = new ReverseLineReader(filename);
var last = lines.Take(2);
OR
Use a System.IO.StreamReader.
string line1, line2;
using(StreamReader reader = new StreamReader("myFile.txt")) {
line1 = reader.ReadLine();
line2 = reader.ReadLine();
}

split a string from a text file into another list

Hi i know the Title might sound a little confusing but im reading in a text file with many lines of data
Example
12345 Test
34567 Test2
i read in the text 1 line at a time and add to a list
using (StreamReader reader = new StreamReader("Test.txt"))
{
string line;
while ((line = reader.ReadLine()) != null)
{
list.Add(line);
}
}
how do i then separate the 1234 from the test so i can pull only the first column of data if i need like list(1).pars[1] would be 12345 and list(2).pars[2] would be test2
i know this sounds foggy but i hope someone out there understands
Maybe something like this:
string test="12345 Test";
var ls= test.Split(' ');
This will get you a array of string. You can get them with ls[0] and ls[1].
If you just what the 12345 then ls[0] is the one to choose.
If you're ok with having a list of string[]'s you can simply do this:
var list = new List<string[]>();
using (StreamReader reader = new StreamReader("Test.txt"))
{
string line;
while ((line = reader.ReadLine()) != null)
{
list.Add(line.Split(' '));
}
}
string firstWord = list[0][0]; //12345
string secondWord = list[0][1]; //Test
When you have a string of text you can use the Split() method to split it in many parts. If you're sure every word (separated by one or more spaces) is a column you can simply write:
string[] columns = line.Split(' ');
There are several overloads of that function, you can specify if blank fields are skipped (you may have, for example columns[1] empty in a line composed by 2 words but separated by two spaces). If you're sure about the number of columns you can fix that limit too (so if any text after the last column will be treated as a single field).
In your case (add to the list only the first column) you may write:
if (String.IsNullOrWhiteSpace(line))
continue;
string[] columns = line.TrimLeft().Split(new char[] { ' ' }, 2);
list.Add(columns[0]);
First check is to skip empty or lines composed just of spaces. The TrimLeft() is to remove spaces from beginning of the line (if any). The first column can't be empty (because the TrimLeft() so yo do not even need to use StringSplitOptions.RemoveEmptyEntries with an additional if (columns.Length > 1). Finally, if the file is small enough you can read it in memory with a single call to File.ReadAllLines() and simplify everything with a little of LINQ:
list.Add(
File.ReadAllLines("test.txt")
.Where(x => !String.IsNullOrWhiteSpace(x))
.Select(x => x.TrimLeft().Split(new char[] { ' ' }, 2)[0]));
Note that with the first parameter you can specify more than one valid separator.
When you have multiple spaces
Regex r = new Regex(" +");
string [] splitString = r.Split(stringWithMultipleSpaces);
var splitted = System.IO.File.ReadAllLines("Test.txt")
.Select(line => line.Split(' ')).ToArray();
var list1 = splitted.Select(split_line => split_line[0]).ToArray();
var list2 = splitted.Select(split_line => split_line[1]).ToArray();

remove blank values from array and suggest a better method to read text file data delimited by '|'

Am trying to get values from a text file in which entries are delimited using '|'.am getting the values using string .Split method..but in some places the delimiter appears multiple times in succession like '||||||||',so empty space gets inserted in the array how should i remove those empty elements from array or is there any efficient technique to read values from text file delimited by '|".below is my code and the screen shot of array values
var reader = new StreamReader(File.OpenRead(#"d:\er.txt"));
while (!reader.EndOfStream)
{
var line = reader.ReadLine().Trim();
var values = line.Split('|');
string[] ee = values;
}
can any one suggest a better method for reading data from text file delimited by '|'
Split has an overload that takes a StringSplitOptions enumeration value:
var values = line.Split(new char[]{'|'}, StringSplitOptions.RemoveEmptyEntries);
This will remove empty entries.
You can use linq on your array?
var values = line.Split("|").Where(v => !string.IsNullOrEmpty(v));
See, the below line of codes, you can do something like that.
var values = line.Split('|');
List<string> FilteredValues = new List<string>();
foreach (var value in values)
{
if (value != "")
{
FilteredValues.Add(value);
}
}
further to Oded's answer this is the correct syntax
var reader = new StreamReader(File.OpenRead(#"d:\er.txt"));
while (!reader.EndOfStream)
{
var line = reader.ReadLine().Trim();
var values = line.Split(new char[]{'|'}, StringSplitOptions.RemoveEmptyEntries);
string[] ee = values;
}
Or, maybe, you can use the trim() function !?

Categories