troubleshooting Question

Calculate a file's size on disk with C#

Avatar of elorc
elorcFlag for United States of America asked on
.NET ProgrammingC#
7 Comments2 Solutions4267 ViewsLast Modified:
I'm trying to calculate a file's size on disk (not simply the file size), but it doesn't seem to be working accurately. I initially used a method described on the MSDN forums, which involved using GetDiskFreeSpace to return cluster size. I took the uint value of lpBytesPerSector and performed the following calculation:

uint TotalSize = lpBytesPerSector * ((FileLength + lpBytesPerSector - 1) / lpBytesPerSector)

The result is inaccurate, however. I run this calculation on all of the files in a particular folder, and it returns a value of 3,491,840 bytes. Windows Explorer indicates that the folder's size on disk is 21,057,536 bytes.

Is there a better or more accurate way to perform this calculation?

Our community of experts have been thoroughly vetted for their expertise and industry experience.

Join our community to see this answer!
Unlock 2 Answers and 7 Comments.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 2 Answers and 7 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros