我写了一小段代码来打开这个文件,我的文件内容如下,每行长度为94个字符,行终止符是\r和\n
101 111111111 1111111111010190542A094101
9000000000001000000000000000000000000000000000000000000
//同样适用于该文本
101 111111111 1111111111010190608A094101
52001 1 1 CCD1 101019101019 1111000020000001 6201110000251 00000000011 1 0111000020000001 820000000100111000020000000000000000000000000000000000000000011 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
}
}但是我在这里没有得到一个错误,谁能告诉我为什么
发布于 2010-10-19 20:29:27
这94个字符是包括还是不包括换行符?字符串"a\r\nb"的长度是四个字符,而不是两个。根据完整的文件内容验证行长度似乎有点困难。例如,可能是文件以\r\n对结尾,也可能不是。我更喜欢单独读取行,并验证每行的修剪长度。
更新
您可以通过将内容与预期的行长进行匹配来验证内容:
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
}然而,这并不是很准确。假设我们需要4个字符的字符串:
string input = "abcd\r\nabcd\r\nabcd";
bool isValid = StringIsValid(input, 4); // returns true看起来没问题。但是,请考虑以下内容:
string input = "abcd\r\nabcd\r\nabcd";
bool isValid = StringIsValid(input, 6); // returns true这也返回true,因为我们检查的唯一一件事是字符串的总长度(在去掉换行符之后)可以均匀地分成6个字符的行。使用12个字符的字符串是可能的,但这并不意味着它实际上是由6个字符的行组成的。因此,更好的方法是检查行的长度。您可以逐行读取,进行验证,如果可以,则将其添加到输出中:
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
}
}
}获取所有行,验证它们的长度,如果它们验证OK,则使用它们(在本例中使用LINQ All扩展方法):...or:
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
}更新2
根据您的注释,这应该适用于您的代码(使用上面示例代码中的LinesHaveCorrectLength方法,只有在所有行都具有预期长度时才会返回true ):
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
strFilePath = openFileDialog1.FileName;
string[] lines = File.ReadAllLines(strFilePath);
if (LinesHaveCorrectLength(lines, 94))
{
// add lines to grid
}
}更新3
LinesHaveCorrectLength的非LINQ版本
private static bool LinesHaveCorrectLength(string[] lines, int expectedLineLength)
{
foreach (string item in lines)
{
if (item.Length != expectedLineLength)
{
return false;
}
}
return true;
}https://stackoverflow.com/questions/3968243
复制相似问题