NullReference Exception in converting string to Char array - c#

It is showing Null Reference Exception on line char[] myChar = read.ToCharArray();.
I am unable to figure out. Please help
class Program
{
static void Main(string[] args)
{
StreamReader myReader = new StreamReader("TextFile1.txt");
string read = "";
while (read != null)
{
read = myReader.ReadLine();
Console.WriteLine(read);
}
char[] myChar = read.ToCharArray();
for (int i = 0; i < myChar.Length; i++)
{
Console.WriteLine(myChar[i]);
}
Console.WriteLine(read);
myReader.Close();
Console.ReadKey();
}
}

The read should be null when the loop is finished and calling ToCharArray on null should give exception. you can put this statement in while loop. I believe you are trying to do some experimentation as you have already printed the string with Console.WriteLine(read);
while ((read = sr.ReadLine()) != null)
{
Console.WriteLine(read);
char[] myChar = read.ToCharArray();
for (int i = 0; i < myChar.Length; i++)
Console.WriteLine(myChar[i]);
}

StringBuilder sb = new StringBuilder();
using (StreamReader sr = new StreamReader("TestFile.txt"))
{
string line;
// Read and display lines from the file until the end of
// the file is reached.
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
sb.Append(line);
}
}
var chars = sb.ToString().ToCharArray();
However, you should add each line into a stringbuilder and then convert it into char array. The thing is what you really want to do?

Related

How to get values from a text file and set them in a Textbox? [duplicate]

This question already has answers here:
C# Put string into TextBox
(3 answers)
Closed 6 years ago.
here is the problem: I've got two classes. Form 1 creates a .txt-File and sets two values (Strings) in it. Now I want to get these two strings by pressing a button(bDirekt), and set each string in a Textbox in Form 2.
Form 1 (should be correct as far as I know, but please tell me if I'm wrong):
public void Txfw()
{
string txBetrag = gBetrag.Text;
string txMonate = gMonate.Text;
string[] vars = new string[] { txBetrag, txMonate };
using (StreamWriter sw = new StreamWriter(#"C:\Users\p2\Desktop\variablen.txt"))
{
foreach (string s in vars)
{
sw.WriteLine(s);
}
}
}
Form 2 (got no idea how to go ahead):
private void bDirekt_Click(object sender, RoutedEventArgs e)
{
using (StreamReader sr = new StreamReader("variables.txt")) ;
string line = "";
while ((line = sr.ReadLine()) != null)
{
monate2.Text =
}
}
I really appreciate your help.
Try this
StringBuilder sb = new StringBuilder();
using (StreamReader sr = new StreamReader(#"C:\Users\p2\Desktop\variablen.txt"))
{
string line;
// Read and display lines from the file until
// the end of the file is reached.
while ((line = sr.ReadLine()) != null)
{
sb.Append((line);
}
}
monate2.Text = sb.Tostring();
UPDATE: To separate line one with rest of the text, you can try this. There are always better ways to achieve this.
StringBuilder sb = new StringBuilder();
string headerLine = string.Empty;
int currentLine = 0;
using (StreamReader sr = new StreamReader(#"C:\Users\p2\Desktop\variablen.txt"))
{
string line;
// Read and display lines from the file until
// the end of the file is reached.
while ((line = sr.ReadLine()) != null)
{
currentLine++; //increment to keep track of current line number.
if(currentLine == 1)
{
headerLine = line;
continue; //skips rest of the processing and goes to next line in while loop
}
sb.Append((line);
}
}
header.Text = headerLine;
monate2.Text = sb.ToString();

how to get two more lines in textfile

i have following code i want this line and next 2 below lines how do this any idea. please help,i want last number please see text below.
static void Main()
{
int counter = 0; string line;
StringBuilder sb = new StringBuilder();
using (System.IO.StreamReader file = new System.IO.StreamReader(#"E:\file\log.txt"))
{
while ((line = file.ReadLine()) != null)
{
if (line.Contains(DateTime.Now.Date.ToShortDateString()))
{
sb.AppendLine(line.ToString());
}
}
}
Console.WriteLine(sb.ToString());
Console.ReadKey();
}
***** INCOMING CALL: 25/04/2016 - 11:45 *****
NAME: Test
NUMBER: (425) 555-1212
***** INCOMING CALL: 25/04/2016 - 11:45 *****
NAME: Test2
NUMBER: (425) 544-1213
Just call file.ReadLine two more times, but it is important to check if the returned string is null because you could reach an unexpected end of file and your code is no more protected by the check in the while condition
...
using (System.IO.StreamReader file = new System.IO.StreamReader(#"E:\file\log.txt"))
{
while ((line = file.ReadLine()) != null)
{
if (line.Contains(DateTime.Now.Date.ToShortDateString()))
{
sb.AppendLine(line);
line = file.ReadLine();
if(line != null) sb.AppendLine(line);
line = file.ReadLine();
if(line != null) sb.AppendLine(line);
}
}
}
If you want to get just the last three lines (assuming that your file is well formatted) then you could add a reset of the StringBuilder inside the loop
using (System.IO.StreamReader file = new System.IO.StreamReader(#"E:\file\log.txt"))
{
while ((line = file.ReadLine()) != null)
{
if (line.Contains(DateTime.Now.Date.ToShortDateString()))
{
// This will remove the previous data and keep
// just the last three lines.....
sb.Length = 0;
sb.AppendLine(line);
line = file.ReadLine();
if(line != null) sb.AppendLine(line);
line = file.ReadLine();
if(line != null) sb.AppendLine(line);
}
}
}
In alternative, but I am not sure if this is a good idea from a performance point of view (in particular if we are talking of a large file), we could use linq in this way
string result = string.Join(Environment.NewLine,
File.ReadLines(#"E:\file\log.txt").Reverse().Take(3));
static void Main()
{
int counter = 0; string line;
List<string> ss = new List<string>();
using (System.IO.StreamReader file = new System.IO.StreamReader(#"E:\file\log.txt"))
{
while ((line = file.ReadLine()) != null)
{
if (line.Contains(DateTime.Now.Date.ToShortDateString()))
{
ss.Add(line);
line = file.ReadLine();
if (line != null)
ss.Add(line);
line = file.ReadLine();
if (line != null)
ss.Add(line);
}
}
}
var item = ss.LastOrDefault();
string number = item.Substring(0, 24).Replace("NUMBER:", "").Trim();
Console.WriteLine(number);
Console.ReadKey();
}

Get strings from the richtext box

I'm here to ask this question again, actually many people replied me their answers in my first question and such question was solved already. But I'm getting a new error about out of bounds exception something. Anyway, I got a new way so I got as well a new question.
How to get some strings from rich text box. Every numbers beside of the characters Q,W,X,Y,Z will be stored in my 5 labels. lbl1,2,3,4,5.
The old regex code is this:
but the error always point to the array element [2].
public void OnAddMessage(string sMessage)
{
richTextBox1.Text = richTextBox1.Text + sMessage;
using (StringReader sr = new StringReader(richTextBox1.Text))
{
string line;
while ((line = sr.ReadLine()) != null)
{
string[] splitContents = regex.Split(line);
frontVal.Text = splitContents[1];
backVal.Text = splitContents[2];
leftVal.Text = splitContents[3];
rightVal.Text = splitContents[4];
tempVal.Text = splitContents[5] + "°C";
}
}
}
This might help to reproduce and solve the problem you asked.
Regex regex = new Regex("[QWXYZ]");
string lines = "Q0.01W0.02X1.23Y5.25Z38.19"
+ Environment.NewLine + "Q0.02W0.32X1.24Y5.22Z32.19";
using (StringReader sr = new StringReader(lines))
{
string line = "";
int lineCount = 0;
while ((line = sr.ReadLine()) != null)
{
lineCount++;
Console.WriteLine("Line " + lineCount.ToString());
string[] splitContents = regex.Split(line).Where(s => s != String.Empty).ToArray();
for(int i = 0; i < splitContents.Length; i++){
Console.WriteLine(splitContents[i]);
}
Console.WriteLine("");
}
}

Scan multiple word from a text file

I have a list of words. I want the program to scan for multiple words from a text file.
This is what i already have:
int counter = 0;
string line;
StringBuilder sb = new StringBuilder();
string[] words = { "var", "bob", "for", "example"};
try
{
using (StreamReader file = new StreamReader("test.txt"))
{
while ((line = file.ReadLine()) != null)
{
if (line.Contains(Convert.ToChar(words)))
{
sb.AppendLine(line.ToString());
}
}
}
listResults.Text += sb.ToString();
}
catch (Exception ex)
{
listResults.ForeColor = Color.Red;
listResults.Text = "---ERROR---";
}
So i want to scan the file for a word, and if it's not there, scan for the next word...
String.Contains() only takes one argument: a string. What your call to Contains(Convert.ToChar(words)) does, is probably not what you expect.
As explained in Using C# to check if string contains a string in string array, you might want to do something like this:
using (StreamReader file = new StreamReader("test.txt"))
{
while ((line = file.ReadLine()) != null)
{
foreach (string word in words)
{
if (line.Contains(word))
{
sb.AppendLine(line);
}
}
}
}
Or if you want to follow your exact problem statement ("scan the file for a word, and if it's not there, scan for the next word"), you might want to take a look at Return StreamReader to Beginning:
using (StreamReader file = new StreamReader("test.txt"))
{
foreach (string word in words)
{
while ((line = file.ReadLine()) != null)
{
if (line.Contains(word))
{
sb.AppendLine(line);
}
}
if (sb.Length == 0)
{
// Rewind file to prepare for next word
file.Position = 0;
file.DiscardBufferedData();
}
else
{
return sb.ToString();
}
}
}
But this will think "bob" is part of "bobcat". If you don't agree, see String compare C# - whole word match, and replace:
line.Contains(word)
with
string wordWithBoundaries = "\\b" + word + "\\b";
Regex.IsMatch(line, wordWithBoundaries);
StringBuilder sb = new StringBuilder();
string[] words = { "var", "bob", "for", "example" };
string[] file_lines = File.ReadAllLines("filepath");
for (int i = 0; i < file_lines.Length; i++)
{
string[] split_words = file_lines[i].Split(' ');
foreach (string str in split_words)
{
foreach (string word in words)
{
if (str == word)
{
sb.AppendLine(file_lines[i]);
}
}
}
}
This works a treat:
var query =
from line in System.IO.File.ReadLines("test.txt")
where words.Any(word => line.Contains(word))
select line;
To get these out as a single string, just do this:
var results = String.Join(Environment.NewLine, query);
Couldn't be much simpler.
If you want to match only whole words it becomes only a little more complicated. You can do this:
Regex[] regexs =
words
.Select(word => new Regex(String.Format(#"\b{0}\b", Regex.Escape(word))))
.ToArray();
var query =
from line in System.IO.File.ReadLines(fileName)
where regexs.Any(regex => regex.IsMatch(line))
select line;

How to skip first line and start reading file from second line in C#

How to start reading file from 2nd line skipping 1st line. This seems to work but is it best way to do so?
using (StreamReader sr = new StreamReader(varFile, Encoding.GetEncoding(1250))) {
string[] stringSeparator = new string[] { "\",\"" };
int i = 0;
while (!sr.EndOfStream) {
string line = sr.ReadLine(); //.Trim('"');
if (i > 0) {
string[] values = line.Split(stringSeparator, StringSplitOptions.None);
for (int index = 0; index < values.Length; index++) {
MessageBox.Show(values[index].Trim('"'));
}
}
i++;
}
}
If the file is not very large and can fit in memory:
foreach (var line in File.ReadAllLines(varFile, Encoding.GetEncoding(1250)).Skip(1))
{
string[] values = line.Split(',');
...
}
If not write an iterator:
public IEnumerable<string> ReadAllLines(string filename, Encoding encoding)
{
using (var reader = new StreamReader(filename, encoding))
{
string line;
while ((line = reader.ReadLine()) != null)
{
yield return line;
}
}
}
and then consume it:
foreach (var line in ReadAllLines(varFile, Encoding.GetEncoding(1250)).Skip(1))
{
string[] values = line.Split(',');
...
}
Could you not just read the first line outside of the loop without assigning it to a variable?
using (StreamReader sr = new StreamReader(varFile, Encoding.GetEncoding(1250))) {
string[] stringSeparator = new string[] { "\",\"" };
if (!sr.EndOfStream)
sr.ReadLine();
while (!sr.EndOfStream) {
string line = sr.ReadLine(); //.Trim('"');
string[] values = line.Split(stringSeparator, StringSplitOptions.None);
for (int index = 0; index < values.Length; index++) {
MessageBox.Show(values[index].Trim('"'));
}
}
}
I'm sorry but I see no problem with the way you are doing it though. I couldn't add comment.
So just for the sake of answering, you probably could have try to call ReadLine() once before the loop. Might not be the best way as I don't know whats the behavior of running ReadLine() if its already end of stream, but it nothing is gonna happen then thats gonna save you some checks.
Updated:
To give a more complete answer, calling ReadLine() when the stream is at its end will return a null.
Reference: http://msdn.microsoft.com/en-us/library/system.io.streamreader.readline.aspx
Remember to check the return for null value.

Categories