1

I try to replace the file name which contains "TEMPDOCUMENTLIBRARY" with "SHAREDDOCS" in the docs (Typed Dataset). But somehow it does not replace it at all. What's wrong ?

for (int index = 0; index < docs.Document.Rows.Count; index++)
{
    if (docs.Document[index].FileName.Contains("TEMPDOCUMENTLIBRARY"))
    {
         docs.Document[index].BeginEdit();
         docs.Document[index].FileName.Replace("TEMPDOCUMENTLIBRARY", "SHAREDDOCS");
         docs.Document[index].EndEdit();
    }
}
0

2 Answers 2

4

Strings are immutable (meaning that the value of a given string never changes). Functions like Substring and Replace return new strings that represent the original string with the desired operations performed.

In order to achieve what you want, you need this:

docs.Document[index].FileName = 
      docs.Document[index].FileName.Replace("TEMPDOCUMENTLIBRARY", "SHAREDDOCS");
Sign up to request clarification or add additional context in comments.

8 Comments

Quick question: You and I understand that strings are immutable, however is it really necessary to have that understanding in order to work with simplistic methods like String.Replace or String.Substring? The function returns the result you want which is basically all anyone using the method should need to know, right?
@M.Babcock - Apparently it is.
@ChaosPandion - I could care less who got the answer, my question is more general then that. We have a lot of experts here on SO that understand what happens under the covers in .NET, but when it comes to simple questions like this one, is it really necessary to force language and education on them that isn't necessary for a general user to have in order to just use the language?
@M.Babcock: I believe that it's beneficial for users to understand why methods work the way they do so that they'll understand more than "If I do X, I get Y." If they know why X produces Y, then they might be able to figure out how to get Z on their own instead of coming back to ask an incremental question. I'm curious why you think a greater understanding is a bad thing? It's not as if I wrote a dissertation on immutability.
@M.Babcock - I would suggest that developers who "have no interest in understanding" why things work the way they do are not good developers!
|
2

String.Replace does not replace in place. Try:

docs.Document[index].FileName = docs.Document[index].FileName.Replace("TEMPDOCUMENTLIBRARY", "SHAREDDOCS");

Notice in the documentation (linked above) that it returns the result of the replace.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.