views:

88

answers:

4

What is the fastest way of getting a file length in .net?

Note: I am accessing files via a network share.

So far I have

  • 1.5ms FileInfo.Length
  • .5ms FileStream().Length
A: 

Why not just use FileInfo.Length?

You could p/invoke the Win32 APIs: CreateFile, GetFileSizeEx, and CloseHandle if you really wanted to.

Brian R. Bondy
@Brian I have re-worded the question to represent my true intent.
Simon
A: 

long size = File.OpenRead(path).Length;

Adi_aks
Server.MapPath() would only apply in ASP.NET, and I'm not sure the fastest way to find a file size would involve unnecessarily opening a stream on it (that, incidentally, is not being closed by this code, too)
Andrew Barber
@Adi better yet to do using (var fileStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read)){ var length = fileStream.Length;}
Simon
+1  A: 

You could PInvoke the FindFirstFile or GetFileAttributesEx API calls, but that seems like a lot of extra work that the FileInfo class is already doing for you. Otherwise I'm wondering the same thing Scott is: why would you not want to use FileInfo?

Daryl Hanson
A: 

Derived from Adi_aks answer

public static long GetFileLength(string path)
{
    using (var fileStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))
    {
        return fileStream.Length;
    }
}
Simon
Why the down vote?
Simon