开发者

Why blank space in my file are missing when i tried to open a file

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;
        openFile开发者_开发问答Dialog1.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


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;
}


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


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.


This one works for me

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜