Search code examples
c#stringwpfpadding

How to add string padding in textbox by importing textfile that has 2 values


This is my code for importing txt file to TextBox (it works). Now my question is how to add string padding like this:

dean harris...........dean.harris@outlook.com

Now it shows just: dean harris, dean.harris@outlook.com.

I looked up a lot but didn't get any good result. I tried using the documentation but I couldn't figure it out. ==> https://learn.microsoft.com/en-us/dotnet/standard/base-types/padding

Thanks in advance!

private void BtnInlezen_Click(object sender, RoutedEventArgs e)
{
    string[] lines = File.ReadAllLines(txtFile);
    try
    {
        using (StreamReader file = new StreamReader(txtFile))
        {
            StringBuilder builder = new StringBuilder();

            while (!file.EndOfStream)
            {
                builder.Append(file.ReadLine().Replace("\"", ""));
                builder.AppendLine();
            }
            
            TxtResultaat.Text = builder.ToString();
        }
    }
    catch (Exception ex)
    {
        if (!File.Exists(txtFile))
        {
            MessageBox.Show(ex.Message, "File not found");
        }
        else
        {
            MessageBox.Show("an unknown error has occurred");
        }
        return;
    }
}

Solution

  • I'm not sure how you want to pad the string so here are two ways. The first center pads the string so they all have the same length and the second aligns the email addresses.

    public static string CenterPad(string s, int maxLength, string delimeter, char replaceWith='.')
    {
        int numDots = maxLength - s.Length + delimeter.Length;
        return s.Replace(delimeter, new string(replaceWith, numDots));
    }
    public static string AlignSecond(string s, int maxLength, string delimeter, char replaceWith='.')
    {
        string [] parts = s.Split(new string[]{delimeter}, StringSplitOptions.None);
        return parts[0].PadRight(maxLength, replaceWith) + parts[1];
    }
    public static void Main()
    {
        string [] tests = {"dean harris, dean.harris@outlook.com",
                           "john smith, john@example.com",
                           "sally washington, sallywashington@example.com"};
        foreach (var s in tests) {
            Console.WriteLine(CenterPad(s, 50, ", "));
        }
        Console.WriteLine();
        foreach (var s in tests) {
            Console.WriteLine(AlignSecond(s, 25, ", "));
        }
    }
    

    Output:

    dean harris................dean.harris@outlook.com
    john smith........................john@example.com
    sally washington.......sallywashington@example.com
    
    dean harris..............dean.harris@outlook.com
    john smith...............john@example.com
    sally washington.........sallywashington@example.com