Question

I am using FileInfo.Length in order to get the size of a file and then post it to a GoogleDoc. The problem is that I am getting negative values from FileInfo.Length....

I have looked around online for some solutions and can't find any other reason...besides the fact that FileInfo.Length should be a Long and I was casting it to an Int.....could this have something to do with it?

Here is my code:

                int size = (int)file.Length;
                string name = file.Name;
                googleBot.insertArchiveRow(name, size);
                progressBar.Value++;
                this.UpdateLayout();

Would casting cause me problems here?

Thanks!

Was it helpful?

Solution

Yes. Casting could cause you problems.

How big is the File?

"FileInfo.Length should be a Long and I was casting it to an Int....."

If greater than 2^31 - 1 then casting to an int could be negative....

e.g.

        long l = (long)Math.Pow(2, 31);
        int i = (int) l;
        Console.WriteLine("{0}", l);
        Console.WriteLine("{0}", i);

Prints:

2147483648
-2147483648

Bottom line: FileInfo.Length is a long , so treat it as such.

OTHER TIPS

Avoid surprises like this and let the compiler generate code to perform error checking:

 int size = checked((int)file.Length);

You'll now get an OverflowException instead of a negative value.

Yeah, pretty easily, in fact...

int.MaxValue ==  2147483647 == 0x7FFFFFFF
int.MinValue == -2147483648 == 0x80000000

int.MaxValue is 2^31 - 1, so something like ~2GB in size; any file bigger than that would read as negative, until you cycled back around again, that is. :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top