Is there a way to programmatically convert VB6 Formatting strings to .NET Formatting strings?

The formatting routine that VB6 uses is actually built into the operating system. Oleaut32.dll, the VarFormat() function. It’s been around for 15 years and will be around for ever, considering how much code relies on it. Trying to translate the formatting strings to a .NET composite formatting string is a hopeless task. Just use the OS function.

Here’s a sample program that does this, using the examples from the linked thread:

using System;
using System.Runtime.InteropServices;

class Program {
    static void Main(string[] args) {
        Console.WriteLine(Vb6Format("hi there", ">"));
        Console.WriteLine(Vb6Format("hI tHeRe", "<"));
        Console.WriteLine(Vb6Format("hi there", ">!@@@... not @@@@@"));
        Console.ReadLine();
    }

    public static string Vb6Format(object expr, string format) {
        string result;
        int hr = VarFormat(ref expr, format, 0, 0, 0, out result);
        if (hr != 0) throw new COMException("Format error", hr);
        return result;
    }
    [DllImport("oleaut32.dll", CharSet = CharSet.Unicode)]
    private static extern int VarFormat(ref object expr, string format, int firstDay, int firstWeek, int flags,
        [MarshalAs(UnmanagedType.BStr)] out string result);
}

Leave a Comment