MtAiryDude
New member
- Joined
- Jan 16, 2023
- Messages
- 2
- Programming Experience
- 10+
I'm pulling my hair out over the following code, which always throws the exception "Offset and length were out of bounds for the array or count is greater than the number of elements from index to the end of the source collection (Parameter 'count')" when it executes the Read() method of the FileStream object fs. When I trace through the code, BytesToRead has the value 16 (which is correct, and matches the number of elements in the iv array). The file named in FilePath exists, is not being accessed by any other process, and is much longer than 16 bytes. What am I doing wrong?
C#:
string FilePath = @"C:\Data\Encryption\Test.txt";
// intervening code omitted
using (FileStream fs = new FileStream (FilePath, FileMode.Open)) //open encrypted file
{
using (Aes aes = Aes.Create()) //create new instance of Aes class
{
byte[] iv = new byte[aes.IV.Length - 1];
int BytesToRead = aes.IV.Length;
int BytesRead = 0;
//read initialization vector from beginning of file
while (BytesToRead > 0)
{
int n = fs.Read(iv, BytesRead, BytesToRead); //THIS LINE ALWAYS THROWS AN EXCEPTION
// balance of while loop omitted
}
// balance of code omitted
}
Last edited by a moderator: