nKognito
nKognito

Reputation: 6363

Get file's size from bytes array (without saving to disc)

I have a byte's array and I want to calculate what would be the file size if I'll write these bytes to file. Is it possible without writing the file to disc?

Upvotes: 73

Views: 112421

Answers (4)

Walter Verhoeven
Walter Verhoeven

Reputation: 4421

some time ago I found this snipped and since then I like to do this

public static string GetSizeInMemory(this long bytesize)
{


    string[] sizes = { "B", "KB", "MB", "GB", "TB" };
    double len = Convert.ToDouble(bytesize);
    int order = 0;
    while(len >= 1024D && order < sizes.Length - 1)
    {
        order++;
        len /= 1024;
    }

    return string.Format(CultureInfo.CurrentCulture,"{0:0.##} {1}", len, sizes[order]);
}

You can use this extension method when accessing anything that provides file or memory size like a FileInfo or a Process, bellow are 2 samples

private void ValidateResources(object _)
{

        Process p = Process.GetCurrentProcess();
        double now = p.TotalProcessorTime.TotalMilliseconds;
        double cpuUsage = (now - processorTime) / MONITOR_INTERVAL;
        processorTime = now;

        ThreadPool.GetMaxThreads(out int maxThreads, out int _);
        ThreadPool.GetAvailableThreads(out int availThreads, out int _);

        int cpuQueue = maxThreads - availThreads;
        var displayString= string.Concat(
                  p.WorkingSet64.GetSizeInMemory() + "/"
                , p.PeakWorkingSet64.GetSizeInMemory(), " RAM, "
                , p.Threads.Count, " threads, ", p.HandleCount.ToString("N0", CultureInfo.CurrentCulture)
                , " handles,  ", Math.Min(cpuUsage, 1).ToString("P2", CultureInfo.CurrentCulture)
                , " CPU usage, ", cpuQueue, " CPU queue depth"

            ));

}

or with a file

    FileInfo file = new FileInfo(pathtoFile);
    string displaySize= file.Length.GetSizeInMemory();

Upvotes: 7

LittleSweetSeas
LittleSweetSeas

Reputation: 7054

Array.Length would give your total size expressed in byte.
Physical dimension on disk may be a little bit more considering cluster size.

Upvotes: 8

Jon Skeet
Jon Skeet

Reputation: 1500695

Um, yes:

int length = byteArray.Length;

A byte in memory would be a byte on disk... at least in higher level file system terms. You also need to potentially consider how many individual blocks/clusters would be used (and overhead for a directory entry), and any compression that the operating system may supply, but it's not clear from the question whether that's what you're after.

If you really do want to know the "size on disk" as opposed to the file size (in the same way that Windows can show the two numbers) I suspect you'd genuinely have to write it to disk - and then use a Win32 API to find out the actual size on disk.

Upvotes: 65

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236228

What about array.Length? Looks like a size in bytes.

Upvotes: 120

Related Questions