2

I am working on C#. I am getting OutOfMemoryException while using string.replace(dt,"") and even for stringbuilder.replace(dt,""). May I please know how to overcome this problem? Or any other way to do the same?

2
  • Can you please elaborate your code? Commented Nov 19, 2009 at 6:24
  • thanks for reply...my problem is that i am using got huge data ....so getting problem in replacing.... Commented Nov 19, 2009 at 6:29

2 Answers 2

1

Since your data is so big, you should not try to operate on it all at once. Instead read in chucks, process it, then write it to disk and move on to the next chunk.

Here is some code (untested):

string current = getChunk();
while (current.Length > 0)
{
    current = current.Replace(oldValue, newValue);
    string toSave = current.Substring(0, current.Length - oldValue.Length);
    saveToFile(toSave);
    current = current.Substring(current.Length - oldValue.Length) + getChunk();
}

I don't save the last oldValue.Length because there is a chance that a replacement might be halfway in one chunk and halfway in another. NOTE: there might be a bug in that code, but it is pretty close.

Sign up to request clarification or add additional context in comments.

Comments

1

Your string is probably way too large and the memory manager fails to find a contiguous block of memory for the new string.

You'll need to optimize your program for more efficient memory management.

4 Comments

thanks for reply ....yes the string that i am using for replace got huge data .....Can u plz suggest me any other way to do the same
Contiguous block of memory shouldn't be reallocated for the StringBuilder as the replace is not increasing the length of the original string. Check the link stackoverflow.com/questions/287842/… for more info
Process the string inside a loop in smaller chunks.
Rashmi Pandit: Had the stringbuilder grown over it's capacity, it'd need to reallocate it's internal buffer.

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.