Search code examples
c#castingfileinfo

Can FileInfo.Length be cast as an integer?


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!


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.