开发者

OutOfMemoryException while using string.replace()

I am working on C#. I am getting OutOfMemoryException while using strin开发者_如何学Cg.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?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜