Search code examples
c#trimmailmessage

C# String.Trim() not removing characters from MailMessage.Subject


I'm trying to eliminate certain symbols from the Subject property of a MailMessage object. What I'm experiencing is that it does nothing. Even after assigning Subject to a string, and trimming that, the final Subject still has the symbols in it. (not showed in example)

MailMessage mailMessage = new MailMessage
{
    From = new MailAddress(mail.SenderEmailAddress),
    SubjectEncoding = System.Text.Encoding.UTF8,
    Subject = mail.Subject.Trim(new char[] {}), //symbol list, like ":", "~", ">"
    Body = mail.Body
};

String path = @"C:\Users\" + Environment.UserName + @"\Documents\EML\";

if (!Directory.Exists(path))
{
    Directory.CreateDirectory(path);
}

path = @"C:\Users\" + Environment.UserName + @"\Documents\EML\"
    + mailMessage.Subject + ".eml";

MessageBox.Show(path);

The message box is just to see whether the symbol gets removed or not at the moment, path will be put into a method later.

mail has subject RE: dog, .Trim tries to remove :,

MessageBox shows C:\Users\user\Documents\EML\RE: dog.eml.


Solution

  • From MSDN:

    String.Trim Method () - Removes all leading and trailing white-space characters from the current String object.

    So, Trim isn't going to remove characters from the middle of a String. Commenters suggested using Replace instead, but there isn't a signature that takes an array of characters like you are using. An easy way around that is Extension methods.

        class Program
        {
    
            static void Main(string[] args)
            {
                string text = "This:is~a>test";
                string subject = text.ReplaceFromCollection(new char[] { ':', '~', '>'}); //symbol list, like ":", "~", ">"
    
                Console.WriteLine($"{text}\n{subject}");
                Console.ReadLine();
            }
    
        }
    
        static class Extensions
        {
            public static String ReplaceFromCollection(this string text, IEnumerable<char> characters)
            {
                foreach (var chr in characters)
                {
                    text = text.Replace(chr.ToString(), String.Empty);
                }
                return text;
            }
        }
    

    Using this, each character in your string that matches a character in the array is replaced with the empty String one by one. The result is then passed back.

    More reading on Extension Methods.