tags:

views:

93

answers:

4

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

     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 any one tell why

+1  A: 

My first try would be File.ReadAllLines and worry about the line lengths later.

jdv
A: 

You are not getting an error because nothing is going wrong. However you need to handle the case where str.Length % 94 != 0 because ReadToEnd will include newlines in your string which is why the mod 94 is not doing the job. An alternative would be to read each line (with ReadLine) and check the length. ReadLine does remove the newline characters.

klausbyskov
If i use ReadLine i can read only one line but what about the other
Dorababu
Just use a loop, reading one line at a time.
klausbyskov
+2  A: 

Is that 94 characters including or excluding the line breaks? The string "a\r\nb" is four characters long, not two. Validating the line lengths based on the full file content seems a bit fragile. It could for instance be that the file ends with a \r\n pair or not. I would prefer to read the lines separately and validate the trimmed length of each line.

Update
You could validate the content by matching it towards the expected line length:

public static bool StringIsValid(string input, int expectedLineLength)
{
    return input.Replace("\r\n", "").Length % expectedLineLength == 0;
}

// called like so:
if (StringIsValid(str, 94))
{
   // do something
}

This is not very accurate though. Let's say we expect 4-character strings:

string input = "abcd\r\nabcd\r\nabcd";
bool isValid = StringIsValid(input, 4); // returns true

That looks OK. However, consider this:

string input = "abcd\r\nabcd\r\nabcd";
bool isValid = StringIsValid(input, 6); // returns true

This also returns true, because the only thing that we check is that the total length of the string (after removing line breaks) could be evenly split up in 6-character lines. With a 12-character string that is possible, but that does not mean that it is in fact made up of lines that are 6 characters long. So, a better approach would be to check the length of the lines instead. Either you read the lines one by one, validating it and adding it to the output if it is OK:

private static bool LineHasCorrectLength(string line, int expectedLineLength)
{
    return line.Length == expectedLineLength;
}

// usage:
using (StreamReader reader = File.OpenText("thefile.txt"))
{
    while (!reader.EndOfStream)
    {
        string line = reader.ReadLine();
        if (LineHasCorrectLength(line, 94))
        {
            // add to output
        }
    }
}

...or you get all lines, validate the length of them, and then use them if they validate OK (in this case by using the LINQ All extension method):

private static bool LinesHaveCorrectLength(string[] lines, int expectedLineLength)
{
    return lines.All(s => s.Length == expectedLineLength);
}

// usage:
string[] lines = File.ReadAllLines("thefile.txt");
if (LinesHaveCorrectLength(lines, 94))
{
    // do something
}

Update 2
Based on your comments, this should work in your code (using the LinesHaveCorrectLength method from the above sample code, which will return true only if all lines have the expected length):

if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
    strFilePath = openFileDialog1.FileName;
    string[] lines = File.ReadAllLines(strFilePath);
    if (LinesHaveCorrectLength(lines, 94))
    {
        // add lines to grid
    }
}

Update 3
Non-LINQ version of LinesHaveCorrectLength:

private static bool LinesHaveCorrectLength(string[] lines, int expectedLineLength)
{
    foreach (string item in lines)
    {
        if (item.Length != expectedLineLength)
        {
            return false;
        }
    }
    return true;
}
Fredrik Mörk
Excluding the line breaks
Dorababu
Then each line will be 96 characters long, given that the last line also ends with the line break.
Fredrik Mörk
I modified my code check once
Dorababu
@Dorababu: after that modification the string will not longer contain any line breaks, so you would need to resort to string parsing to populate the grid. I would still go for the option to read the file line by line.
Fredrik Mörk
But it works if i have more than two lines in my file why this happens
Dorababu
If the code does not work for all my case then i can change it but it works in few cases as i mentioned
Dorababu
@Dorababu: see my updated answer.
Fredrik Mörk
Hey i got it by declaring a boolean variable
Dorababu
Hi one more thing your code will works if one of the statement is true means if a line consists of 94 and if another doesn't it works but i need to write only if all line is my file satisfy the condition
Dorababu
@Dorababu: see second update.
Fredrik Mörk
I used this method LinesHaveCorrectLength in the later one i did not get what s is meant for so can you make an edit and tell
Dorababu
@Dorababu: it's the input parameter to the lambda expression. Essentially the code to the right of the `=>` will be called for each string in `lines`. `s` is the input parameter, that will hold the value for each call.
Fredrik Mörk
I am not using LINQ
Dorababu
I am using framework 2.0
Dorababu
@Dorababu: updated with a non-LINQ version of that method. BTW, it's a good idea to mention restrictions like .NET 2.0 in the question. After all, it's been a few years since 3.5 was released.
Fredrik Mörk
Ok thanks for your code :)
Dorababu
A: 

This one works for me

while (sr.Peek() >= 0)
{
  str = sr.ReadLine().Replace("\r", "").Replace("\n", "");
  length += str.Length;
}
Dorababu