tags:

views:

32

answers:

1

Hi!, how can I call the StrFormatByteSize64 function from the Win API from within C#? I'm trying the following code, but without success:

[DllImport("shlwapi.dll")]
static extern void StrFormatByteSize64(ulong qdw, char[] pszBuf, uint cchBuf);

char[] temp = new char[128];
ulong size = 2000;
StrFormatByteSize64(size, temp, 128);
Console.WriteLine(temp);

The function's documentation can be found here: http://msdn.microsoft.com/en-us/library/bb759971%28VS.85%29.aspx

Thank you!

A: 

This works, although it may not be the cleanest way:

using System;
using System.Runtime.InteropServices;
using System.Text;

public class Test
{    
    [DllImport("shlwapi.dll")]
    static extern void StrFormatByteSize64(ulong qdw, StringBuilder builder,
                                           uint cchBuf);

    static void Main()
    {
        ulong size = 2000;
        StringBuilder builder = new StringBuilder(128);
        StrFormatByteSize64(size, builder, 128);
        Console.WriteLine(builder);
    }
}

I'm afraid I don't know much about interop - it could be that you don't need to specify the initial capacity of the StringBuilder, for example. I'm not sure :( Anyway, it should provide you with a starting point for further investigation.

Jon Skeet
Thank you! It works pretty well. Finally a nice solution to convert bytes to other memory units, such as KB, MB, GB... I'll investigate further the matter of the StringBuilder class.
Luís Mendes