How to Read an Entire File to a String Using C#

How to read an entire file to a string using C#?

How about File.ReadAllText:

string contents = File.ReadAllText(@"C:\temp\test.txt");

How can I read any file into a string

Using your code from the original question and opening a file, does show the entire stream (when looking it in debugger) - The problem is that most of these binary files have null terminators (\0 char) which will cause most viewers to stop reading the contents of the stream.

If you remove/escape the '\0' you'll see the entire stream just like in notepad.

For example:

string filePath = @"c:\windows\system32\calc.exe";
StreamReader sr = new StreamReader(filePath);
string text = sr.ReadToEnd();
sr.Close();

textBox1.Text = text.Replace('\0', ' ');

Add a textbox1 to a form and see for yourself... You'll see the entire stream...

Read file contents into string, not string array

Use the

File.ReadAllText()

You can find more information on the MSDN site

http://msdn.microsoft.com/en-us/library/system.io.file.readalltext(v=vs.110).aspx

How best to read a File into List string

var logFile = File.ReadAllLines(LOG_PATH);
var logList = new List<string>(logFile);

Since logFile is an array, you can pass it to the List<T> constructor. This eliminates unnecessary overhead when iterating over the array, or using other IO classes.

Actual constructor implementation:

public List(IEnumerable<T> collection)
{
...
ICollection<T> c = collection as ICollection<T>;
if( c != null) {
int count = c.Count;
if (count == 0)
{
_items = _emptyArray;
}
else {
_items = new T[count];
c.CopyTo(_items, 0);
_size = count;
}
}
...
}

C# reading a string from text file, splitting and putting into tabstring

Your problem is here:

while (srListOfObjects.ReadLine() != null)
{
string myString= (srListOfObjects.ReadLine();

You are entering the loop on the condition that srListOfObjects.ReadLine() returns something other than null but then you are immediately reading a new line form srListOfObjects and storing the returned reference in myString. This has obviously two problems:

  1. The second call to ReadLine can return null and you are not checking if it is. The error you are getting is due to this reason.
  2. You are losing information. You are ignoring the line you are reading when checking the while condition. Until your program crashes or runs to the end (depends on wether the input file has even or odd number of lines), you will process only half of the data.

Update:
You should only read one line per iteration. One way to do it is declaring and initializing myString before entering the loop and updating it on every iteration:

var myString = srListOfObjects.ReadLine();

while (myString != null)
{
//do your stuff
myString = srListOfObjects.ReadLine();
}

How to read a file into a string with CR/LF preserved?

Are you sure that those methods are the culprits that are stripping out your characters?

I tried to write up a quick test; StreamReader.ReadToEnd preserves all newline characters.

string str = "foo\n\r\nbar";
using (Stream ms = new MemoryStream(Encoding.ASCII.GetBytes(str)))
using (StreamReader sr = new StreamReader(ms, Encoding.UTF8))
{
string str2 = sr.ReadToEnd();
Console.WriteLine(string.Join(",", str2.Select(c => ((int)c))));
}

// Output: 102,111,111,10,13,10,98,97,114
// f o o \n \r \n b a r

An identical result is achieved when writing to and reading from a temporary file:

string str = "foo\n\r\nbar";
string temp = Path.GetTempFileName();
File.WriteAllText(temp, str);
string str2 = File.ReadAllText(temp);
Console.WriteLine(string.Join(",", str2.Select(c => ((int)c))));

It appears that your newlines are getting lost elsewhere.

Read Certain Data from text File

You can use Regex with LINQ to compare the Date format data type.

CODE

// Regex pattern to match DD.MM.YYYY Format
var regexPattern = @"^([0]?[0-9]|[12][0-9]|[3][01])[.]([0]?[1-9]|[1][0-2])[.]([0-9]{4}|[0-9]{2})$";
Regex regexObj = new Regex(regexPattern);
// Matched Values matching the regex pattern are returned in IENUMERABLE OF STRING TYPE
var dates = File.ReadLines(txtFilePath).Select(lines => lines.Split(' ').FirstOrDefault(colValue => regexObj.IsMatch(colValue)));


Related Topics



Leave a reply



Submit