Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to get the size of a file in .NET using a static method?

I know the normal way of getting the size of a file would be to use a FileInfo instance:

using System.IO; class SizeGetter {   public static long GetFileSize(string filename)   {     FileInfo fi = new FileInfo(filename);     return fi.Length;   } } 

Is there a way to do the same thing without having to create an instance of FileInfo, using a static method?

Maybe I'm trying to be overly stingy with creating a new instance every time I want a file size, but take for example trying to calculate the total size of a directory containing 5000+ files. As optimized as the GC may be, shouldn't there be a way to do this without having to tax it unnecessarily?

like image 712
Will Avatar asked Sep 28 '11 13:09

Will


People also ask

How do I get the size of a file in C#?

Get File Size With the FileInfo. The FileInfo class provides methods for creating, opening, copying, deleting, and moving files in C#. The FileInfo. Length property gets the size of a file in bytes.

What is file IO C#?

Advertisements. A file is a collection of data stored in a disk with a specific name and a directory path. When a file is opened for reading or writing, it becomes a stream. The stream is basically the sequence of bytes passing through the communication path.

How do you create a .NET file?

The Create() method of the File class is used to create files in C#. The File. Create() method takes a fully specified path as a parameter and creates a file at the specified location; if any such file already exists at the given location, it is overwritten.


2 Answers

Don't worry about it. First, allocation in .NET is cheap. Second, that object will be in gen 0 so it should be collected without much overhead.

like image 114
Dmitry Avatar answered Oct 08 '22 20:10

Dmitry


Don't worry about it.

  • I've found a blog post of someone who measured the overhead of object creation in .NET (C# Object Creation Time Trials), and, as it turns out, creating 10,000 objects took 0.03 seconds, i.e., 3 µs per object. The time required to read the file length from the file system will surely dominate those 3 microseconds significantly.

  • A lot of static methods in the .NET framework internally create objects and call instance methods on them (you can verify this by looking at the reference source or by using some reflection tool). You assume that a static method is faster. Do not make such assumptions. If you have two ways to do the same thing, measure which one is faster.

like image 21
Heinzi Avatar answered Oct 08 '22 20:10

Heinzi