2

I faced some strange issue, I don't really know if this is the expected behavior or a bug.

I just randomly created a file stream, which is not an image stream, some other file stream like pdf/doc etc. The file stream was opened in a writable mode. It happened that my other part of the code, set the position of the file stream to a large value which is beyond the length of the actual file stream, due to some reasons.

Then I called Bitmap's constructor by passing this file stream, and actual file which is stored on disk is changed and file size became too huge. When I opened the modified file and checked, I noticed that Bitmap class is padding null characters when the position of the file stream is beyond its length. File size is becoming equal to the position value which I was set. Then I noticed that it happens with any file which I pass, including image files.

Here is the code:

        Bitmap bitmap = null;
        FileStream fs = new FileStream(@"C:\\sampleFile.ext", FileMode.Open, FileAccess.ReadWrite);
        try
        {               
            fs.Position = fs.Length * 100;               
            bitmap = new Bitmap(fs);
        }
        catch (Exception)
        {
            if (bitmap != null)
                bitmap.Dispose();
            fs.Dispose();
        }

My doubt is is this the known behavior?

3 Answers 3

4

From the docs of FileStream.Position:

Seeking to any location beyond the length of the stream is supported. When you seek beyond the length of the file, the file size grows.

So, yes, it's documented and expected behavior.

1
  • And so the focus in Bitmap in the question is all a red herring? Jul 17, 2014 at 7:51
1

It is an expected behavior as the file is opened in ReadWrite mode and position is intended to be positioned to the offset desired. Since file position is pointing to the specified location file is padded with zero bytes when the file is needed to be read by some other object, Bitmap in this case.

0

Yes. It's known behavior.

Seeking to any location beyond the length of the stream is supported. When you seek beyond the length of the file, the file size grows. In Microsoft Windows NT and newer, any data added to the end of the file is set to zero.

Form MSDN

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.