5

Currently I'm trying to print some information in the console, but I'm trying to give all results the same padding.

Here an example, you can see CurrentBuildNumber result has one /t to much. /t is only to align everything out, it could be anything else. Example screenshot

So, i need a "fixed" padding for the : [result]. How can i do this correctly in my code?

Thanks!

Code:

        RegistryKey registryKeys = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion");

        foreach (string registryKey in registryKeys.GetValueNames())
        {
            Console.WriteLine(registryKey + "\t\t: " + registryKeys.GetValue(registryKey));
        }
3
  • In the screenshot? :P Wait, I'll add.
    – Wouter0100
    Commented Nov 14, 2013 at 21:35
  • 1
    Thanks. The help center pages specifically say "Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance." (emphasis mine). A screen image is not "code in the question itself" (just for future reference). :)
    – Ken White
    Commented Nov 14, 2013 at 21:38
  • I'm sorry! Thanks for the notice :)
    – Wouter0100
    Commented Nov 14, 2013 at 21:44

4 Answers 4

13

Use string.Format() or just Console.Write() as it has support for formats

const string format = "{0,-32} :{1}";

Console.WriteLine(format, "Key", "Value")

the format value -32 means that key should take 32 positions and aligned to the left.

0
8

Use .PadRight(30) on the labels for example.

https://learn.microsoft.com/en-us/dotnet/api/system.string.padright?view=netframework-4.8

1
  • Thanks! This answered my question :). Damn, that i didn't find this on internet!
    – Wouter0100
    Commented Nov 14, 2013 at 21:40
1

Try this:

var key = "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion";
RegistryKey registryKeys = 
    Registry.LocalMachine.OpenSubKey(key);
var maxLength = registryKeys.GetValueNames().Max(n => n.Length);
foreach (string registryKey in registryKeys.GetValueNames())
{
    Console.WriteLine("{0}:{1}", 
        registryKey.PadRight(maxLength), 
        registryKeys.GetValue(registryKey));
}
0

Console.WriteLine(registryKey.PadRight(20, ' ') + registryKeys.GetValue(registryKey));

http://msdn.microsoft.com/en-us/library/66f6d830(v=vs.110).aspx

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.