Click here to Skip to main content
15,898,134 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi all, I write a small code to open the file my file contents are as follows each line length is 94 characters and line terminator is \r and \n

101 111111111 1111111111010190542A094101
9000000000001000000000000000000000000000000000000000000

// same Works for this text

101 111111111 1111111111010190608A094101
52001 1 1 CCD1 101019101019 1111000020000001 6201110000251 00000000011 1 1 0111000020000001 820000000100111000020000000000000000000000011 111000020000001 9000001000001000000010011100002000000000001000000000000

C#
private void mnuOpen_Click(object sender, EventArgs e)
    {
        string strFilePath = string.Empty;
        OpenFileDialog openFileDialog1 = new OpenFileDialog();
        openFileDialog1.FileName = string.Empty;
        openFileDialog1.RestoreDirectory = true;
        if (openFileDialog1.ShowDialog() == DialogResult.OK)
        {
            strFilePath = openFileDialog1.FileName;
            StreamReader sr = new StreamReader(strFilePath);
            string str = string.Empty;
            str = sr.ReadToEnd().Replace("\r", "").Replace("\n", "");
            sr.Close();
            if (str.Length % 94 == 0)
            {
                 //Do some thing
             }
           }


But I am not getting an error here, can anyone tell why?
Posted
Updated 19-Oct-10 22:28pm
v2

1 solution

The lines of data you have shown are not 94 characters per line.If you concatenate the first two, it is 95.
Check your inputs.

1) Don't use "magic numbers" - 94 is one in your code. Why is it 94? Answer: because that is the data size. So use a constant, and call it "dataSize" of similar. That way, if the data size changes, you only have to change it in one place.

2) If you are working with line-based data, then read it as lines:
C#
string[] lines = File.ReadAllLines(openFileDialog1.FileName);
Will read your whole file, without worrying about streams, and place each line into a separate string, removing the \r and \n for you. You can then process each group of data separately, and report errors for individual "bad lines". You should not faff about with line terminators: they are not the same for all systems. The system you are working on knows what lines end with - use it!
 
Share this answer
 
Comments
demouser743 20-Oct-10 4:35am    
Thanks

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900