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?
-
Can you please elaborate your code?Rashmi Pandit– Rashmi Pandit2009-11-19 06:24:23 +00:00Commented Nov 19, 2009 at 6:24
-
thanks for reply...my problem is that i am using got huge data ....so getting problem in replacing....MGK– MGK2009-11-19 06:29:54 +00:00Commented Nov 19, 2009 at 6:29
2 Answers
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.
Comments
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.