Replace string regardless of capitals

100 views Asked by At

I have this variable defined:

string string2remove ="slimshady";

I have a string filePath that has the value myNameIsslimshady

Path.GetFileNameWithoutExtension(filePath.Replace(string2remove,"")) gives me mynameis

However, when filePath has the value myNameIsSlimShady Path.GetFileNameWithoutExtension(filePath.Replace(string2remove,"")) gives me myNameIsSlimShady

Apparently replace cares about capitalisation. No problem! I will make filePath all lowercase using ToLower().

Path.GetFileNameWithoutExtension(filePath.ToLower().Replace(string2remove,""))

Now I get mynameisslimshady. All in lower but slimshady still has not left the building.

How do I get the replace to ignore capitalisation?

Full code below

<FileFormats>
    <#
    foreach (string filePath in myFiles)
    {
            bool fHasSpace = filePath.Contains(" ");
            if  (fHasSpace) {} else {
          
            #>

    <FlatFileFormat Name="FlatFileFormat_<#=Path.GetFileNameWithoutExtension(filePath.ToLower().Replace(string2remove,""))#>" RowDelimiter="<#=delimiter#>" ColumnNamesInFirstDataRow="true" IsUnicode="false">
        <Columns>
            <# 
                 
                StreamReader myFile = new StreamReader(filePath);
                myColumns = myFile.ReadLine().Replace(separator,"").Split(delimiter);
                 myFile.Close();
                 
                // to determine the column delimiter 
                int columnCount = 0;
                string columnDelimiter = "";
 
                    foreach(string myColumn in myColumns)
                    {
                        string str_delimiter = delimiter.ToString();
                        columnCount++;
                        bool finalColumn = columnCount == myColumns.Length;
                        if (finalColumn)
                        {
                            columnDelimiter = "CRLF";
                        }
                        else
                        {   columnDelimiter = str_delimiter;
                        }
                #>
                <Column Name="<#=myColumn#>" DataType = "<#=imp_datatype#>" Length="<#=imp_length#>" Delimiter="<#=columnDelimiter#>"></Column>
                <# } #>
            </Columns>
        </FlatFileFormat>
            <#}}#>
    </FileFormats>
2

There are 2 answers

0
Henrov On BEST ANSWER

I ended up using

fileName=Regex.Replace(Path.GetFileNameWithoutExtension(filePath), string2remove,"", RegexOptions.IgnoreCase);
0
Gec On

Try using the overload that has a StringComparison parameter.

This code writes myNameIs to the console:

        string toReplace = "slimshady";
        string original = "myNameIsSlimShady";
        string outcome = original.Replace(toReplace, "", StringComparison.OrdinalIgnoreCase);
        Console.WriteLine(outcome);   // outputs myNameIs