我定义了这个变量:
string string2remove ="slimshady";
我有一个值为myNameIsslimshady
的字符串filePath
Path.GetFileNameWithoutExtension(filePath.Replace(string2remove,""))
给我mynameis
但是,当filePath的值为myNameIsSlimShady
时Path.GetFileNameWithoutExtension(filePath.Replace(string2remove,""))
给我myNameIsSlimShady
显然,replace关心资本化。没问题!我将使用ToLower()
使filePath全部小写。
Path.GetFileNameWithoutExtension(filePath.ToLower().Replace(string2remove,""))
现在我得到mynameisslimshady
。一切都在下面,但阴凉处仍然没有离开大楼。
如何让替换忽略资本化?
以下的完整代码
<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>
尝试使用具有StringComparison参数的重载。
此代码将myNameIs写入控制台:
string toReplace = "slimshady";
string original = "myNameIsSlimShady";
string outcome = original.Replace(toReplace, "", StringComparison.OrdinalIgnoreCase);
Console.WriteLine(outcome); // outputs myNameIs
我最终使用了
fileName=Regex.Replace(Path.GetFileNameWithoutExtension(filePath), string2remove,"", RegexOptions.IgnoreCase);