Search code examples
c#vb.netsymbolswords

Skip words / symbols when reading file


I'm making a small C# app and I have a small issue .

I have a .xml with plain text and I need only the 4th line .

string filename = "file.xml";
if (File.Exists(filename))
{
    string[] lines = File.ReadAllLines(filename);
    textBox1.Text += (lines[4]);
}

Till now everything is good, my only problem is that I have to remove from the 4th line some words and symbols .

My bad words and symbols :

word 1 
: 
' 
, 

I'v been looking on google however I couldn't find anything for C#. Found a code for VB , but I'm new in this and I really don't know how to convert it and make it working.

 Dim crlf$, badChars$, badChars2$, i, tt$
  crlf$ = Chr(13) & Chr(10)
  badChars$ = "\/:*?""<>|"           ' For Testing, no spaces
  badChars2$ = "\ / : * ? "" < > |"  ' For Display, has spaces

  ' Check for bad characters
For i = 1 To Len(tt$)
  If InStr(badChars$, Mid(tt$, i, 1)) <> 0 Then
    temp = MsgBox("A directory name may not contain any of the following" _
           & crlf$ & crlf$ & "     " & badChars2$, _
           vbOKOnly + vbCritical, _
           "Bad Characters")
    Exit Sub
  End If
Next i

Thank you.

FIXED :)

 textBox1.Text += (lines[4]
              .Replace("Word 1", String.Empty)
            .Replace(":", String.Empty)
            .Replace("'", String.Empty)
            .Replace(",", String.Empty));

Solution

  • You could replace them with nothing:

    textBox1.Text += lines[4].Replace("word 1 ", string.Empty)
                             .Replace(":", string.Empty)
                             .Replace("'", string.Empty)
                             .Replace(",", string.Empty);
    

    Or perhaps create an array of expressions you want removed, and replace them all with nothing.

    string[] wordsToBeRemoved = { "word 1", ":", "'", "," };
    
    string result = lines[4];
    foreach (string toBeRemoved in wordsToBeRemoved) {
        result = result.Replace(toBeRemoved, string.Empty);
    }
    textBox1.Text += result;