Daniel Flannery
Daniel Flannery

Reputation: 1178

C# Detecting null characters in a string array

I am reading in from a text file using StreamReader into a string array text[]. One of the lines in the textfile is being read in as "\0" in positions 1 -> 20 of the array. How would I go about detecting this null character and ignoring this line.

Code example:

StreamReader sr = new StreamReader(Convert.ToString(openFileDialog1.FileName));
while (!sr.EndOfStream)
{
    string l= sr.ReadLine();
    string[] parsedLine = l.Split(new char[] { '=' },StringSplitOptions.RemoveEmptyEntries);
    // Not working:
    if (parsedLine.Length == 0)
    {
        MessageBox.Show("Ignoring line");
    }

Any help would be great!

Upvotes: 4

Views: 13319

Answers (5)

Estefany Velez
Estefany Velez

Reputation: 328

Use the built-in String.IsNullOrEmpty() method:

if (!string.IsNullOrEmpty(l))
{
    // your code here
}

Upvotes: 1

Me.Name
Me.Name

Reputation: 12544

Assuming you mean a character with ascii code: 0

   if (parsedLine.Length == 0 || parsedLine[0] == '\0')continue;

edit the above will work if parsedLine is a string, but for the parsing in your code:

    string[] parsedLine = l.Split(new char[] { '=' },StringSplitOptions.RemoveEmptyEntries)
                      .Where(s=>s.Length != 1 || s[0] != '\0').ToArray();

Upvotes: 3

Joel Etherton
Joel Etherton

Reputation: 37543

Here is a linq solution that should work:

StreamReader sr = new StreamReader(Convert.ToString(openFileDialog1.FileName));
while (!sr.EndOfStream)
{
    string l= sr.ReadLine();
    bool nullPresent = l.ToCharArray().Any(x => x.CompareTo('\0') == 0);

    if (nullPresent)
    {
        MessageBox.Show("Ignoring line");
    }
    else
    {
        // do other stuff
    }
}

Upvotes: 1

xdazz
xdazz

Reputation: 160933

string l= sr.ReadLine();
if (l == "") {
  MessageBox.Show("Ignoring line");
  continue;
}

Upvotes: 0

bruno conde
bruno conde

Reputation: 48255

Just ignore the line if it contains the null character.

string l = sr.ReadLine();
if (string.IsNullOrEmpty(l) || l[0] == '\0'))
   continue;
...

Upvotes: 1

Related Questions