Muflix
Muflix

Reputation: 6798

Ignoring NUL value when reading textfile

I have this kind of tab delimited textfile

enter image description here

which i need to format to .CSV and Iam reading it like that

public static void ReadDelimitedFile(string docPath)
        {
            using (var writer = File.CreateText(@"outputFile.csv"))
            {
                using (var file = new StreamReader(docPath))
                {
                    string line;
                    while ((line = file.ReadLine()) != null)
                    {
                        if (!string.IsNullOrEmpty(line))
                        {
                            var delimiters = new char[] { '\t' };
                            var segments = line.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);

                            foreach (var segment in segments)
                            {
                                writer.Write(segment+";");
                            }
                            writer.WriteLine();
                        }
                    }
                }
            }
        } 

I tried to use static method

if (!string.IsNullOrEmpty(line))

but it does not ignore the NUL lines, how can i get rid of them ? What that symbol even mean ?

Thank you

Upvotes: 0

Views: 718

Answers (3)

Thorsten Dittmar
Thorsten Dittmar

Reputation: 56697

Try to use

line = line.Trim('\0');
if (!String.IsNullOrEmpty(line))
    ....

Trim should remove any leading or trailing nul-characters from the string. To be totally sure to only remove the nul at the end of a line, use

line = line.TrimEnd('\0');

Upvotes: 2

Konrad Kokosa
Konrad Kokosa

Reputation: 16878

I would change it to something like:

if (!string.IsNullOrEmpty(line) && line.First() != 0x00)

Upvotes: 2

Beachwalker
Beachwalker

Reputation: 7915

Try to compare with System.Text.Encoding.ASCII.GetChars(new byte[] {00}) or Convert.ToChar(0) instead. This should give you the null character ('\0') to compare with.

Upvotes: 0

Related Questions