P basak
P basak

Reputation: 5004

Reading from a file in C# without the newline character

i want to read from a text file in C#. But I want all the lines in the file to be concatenated into one line.

for example if i have in the file as

ABCD

EFGH

I need to read ABCDEFGH as one line.

I can do this by reading one line at a time from the file and concatenating that line to a string in a loop. But are there any faster method to do this?

Upvotes: 4

Views: 16370

Answers (4)

ionden
ionden

Reputation: 12786

Use this:

using (System.IO.StreamReader myFile = new System.IO.StreamReader("test.txt")) {
   string myString = myFile.ReadToEnd().Replace(Environment.NewLine, "");
}

Upvotes: 6

Desolator
Desolator

Reputation: 22779

string file = File.ReadAllText("text.txt").Replace("\r\n", " ");

Upvotes: 1

YoryeNathan
YoryeNathan

Reputation: 14532

string.Join(" ", File.ReadAllLines("path"));

Replace " " with "" or any other alternative "line-separator"

Example file:

some line

some other line

and yet another one

With " " as separator: some line some other line and yet another one

With "" as separator: some linesome other lineand yet another one

Upvotes: 9

clearpath
clearpath

Reputation: 956

What is a one line for you?

If you want to put the entire content of a file into a string, you could do

string fileContent  = File.ReadAllText(@"c:\sometext.txt");

If you want your string without newline characters you could do

fileContent = fileContent.Replace(Environment.NewLine, " ");

Upvotes: 0

Related Questions