I'm reading in a text file using BinaryReader, then doing what I want with it (stripping characters, etc..), then writing it out using BinaryWriter.
Nice and simple.
One of the things I need to do before I strip anything is to:
Check that the amount of characters in the file is even (obviously file.Length % 2) and
If the length is even, check that every preceding character is a zero.
For example:
0, 10, 0, 20, 0, 30, 0, 40.
I need to verify that every second character is a zero.
Any ideas? Some sort of clever for loop?
OKAY!
I need to be a lot more clear about what I'm doing. I have file.txt that contains 'records'. Let's just say it's a comma delimited file. Now, What my program needs to do is read through this file, byte by开发者_如何学C byte, and strip all of the characters we don't want. I have done that. But, some of the files that will be going through this program will be single byte, and some will be double byte. I need to deal with both of these possibilities. But, I need to figure out whether the file is single or double byte in the first place.
Now, obviously if the file is double byte:
- The file length will be divisible by 2 and
- Every preceding character will be a zero.
and THAT'S why I need to do this.
I hope this clears some stuff up..
UPDATE!
I'm just going to have a boolean in the arguments - is16Bit. Thanks for your help guys! I would have rather deleted the question but it won't let me..
Something like this in a static class:
public static IEnumerable<T> EveryOther(this IEnumerable<T> list)
{
bool send = true;
foreach(var item in list)
{
if (send) yield return item;
send = !send;
}
}
and then (using the namespace of the previous class)
bool everyOtherIsZero = theBytes.EveryOther().All(c => c == 0);
string[] foo = file.text.Split(new{','}, StringSplitOptions.RemoveEmptyEntries);
for(int i=0; i<foo .Length; i+=2)
{
if(file[i]!="0")
return false;
}
How about this
string content = File.ReadAllText(@"c:\test.txt");
if (content.Length % 2 != 0)
throw new Exception("not even");
for(int i = 0; i < content.Length; i+=2)
if (content[i] != '0')
throw new Exception("no zero found");
精彩评论