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?
Asked
Active
Viewed 4,535 times
2
-
Can you please elaborate your code? – Rashmi Pandit Nov 19 '09 at 06:24
-
thanks for reply...my problem is that i am using got huge data ....so getting problem in replacing.... – MGK Nov 19 '09 at 06:29
2 Answers
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.

arul
- 13,998
- 1
- 57
- 77
-
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 – MGK Nov 19 '09 at 06:28
-
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 http://stackoverflow.com/questions/287842/is-stringbuilder-replace-more-efficient-than-string-replace for more info – Rashmi Pandit Nov 19 '09 at 06:29
-
-
Rashmi Pandit: Had the stringbuilder grown over it's capacity, it'd need to reallocate it's internal buffer. – arul Nov 19 '09 at 06:31
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.

tster
- 17,883
- 5
- 53
- 72