1

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.

0

4 Answers 4

12

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);
Sign up to request clarification or add additional context in comments.

1 Comment

To elaborate: This is because strings are immutable, so if you ever call a method to change one, what actually happens is that the method returns the changed string and the original string is unmodified.
3

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.

Comments

1

In

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

just do the below change:

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

Comments

1

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);
 }

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.