简体   繁体   中英

String.Replace in C# .NET

I would like to know why it is not working:

string filename = optionFileNameFormat; // "{year}-{month}-{day} {name}"
Dictionary<string, string> tagList = new Dictionary<string, string>();
tagList.Add("author",System.Security.Principal.WindowsIdentity.GetCurrent().Name);
tagList.Add("year" , "" + DateTime.Now.Year);
tagList.Add("month", "" + DateTime.Now.Month);
tagList.Add("day"  , "" + DateTime.Now.Day);

foreach (var property in tagList)
{
    filename.Replace(@"{" + property.Key + @"}", property.Value);
}

I don't have any error, but my string doesn't change.

There may be other problems as well, but what jumped out at me right away is that the Replace() function does not change the string . Instead, it returns a new string. Therefore, you need to assign the result of the function back to the original:

filename = filename.Replace(@"{" + property.Key + @"}", property.Value);

The String.Replace method returns a new string. It doesn't change the original string.

Returns a new string in which all occurrences of a specified Unicode character or String in the current string are replaced with another specified Unicode character or String

So, you should assign a new string or an existing one inside your foreach loop:

filename = filename.Replace(@"{" + property.Key + @"}", property.Value);

or

string newfilename = filename.Replace(@"{" + property.Key + @"}", property.Value);

And remember, in .NET, strings are immutable types . You can't change them. Even if you think you change them, you create new string objects.

In

foreach (var property in tagList)
{
    filename.Replace(@"{" + property.Key + @"}", property.Value);
}

just do the below change:

filename =  filename.Replace(@"{" + property.Key + @"}", property.Value);

This is the completed code:

 string filename = optionFileNameFormat; // "{year}-{month}-{day} {name}"
 Dictionary<string, string> tagList = new Dictionary<string, string>();
 tagList.Add("author",System.Security.Principal.WindowsIdentity.GetCurrent().Name);
 tagList.Add("year" , "" + DateTime.Now.Year);
 tagList.Add("month", "" + DateTime.Now.Month);
 tagList.Add("day"  , "" + DateTime.Now.Day);

 foreach (var property in tagList)
 {
     filename= filename.Replace(@"{" + property.Key + @"}", property.Value);
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM