I can’t get the StringBuilder Replace to work. Here is my simplified code:
[Code]
private static string segment = “1234567890”;
public static string oldValue = “—”;
public static string newValue = “======”;
public static string source = null;
public static string dest = null;
public static void Main()
{
Debug.EnableGCMessages(false);
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= 10; i++)
{
sb.Append(segment.Substring(0, i));
sb.Append(oldValue);
}
source = sb.ToString();
TimeSpan startTime = new TimeSpan();
TimeSpan endTime = new TimeSpan();
Debug.Print("");
Debug.Print("Test 1: string replace using StringBuilder.Replace...");
sb.Clear();
sb = null;
dest = null;
Debug.GC(true);
Debug.Print(" Free mem before : " + Debug.GC(false).ToString());
startTime = Utility.GetMachineTime();
sb = new StringBuilder(source);
sb.Capacity = source.Length * 50;
sb.Length = source.Length * 50;
Debug.Print(" Capacity = " + sb.Capacity);
sb.Replace(oldValue, newValue);
dest = sb.ToString();
endTime = Utility.GetMachineTime();
Debug.Print(" Free mem after : " + Debug.GC(false).ToString());
Debug.Print(" Elapsed msecs : " + (((double)endTime.Subtract(startTime).Ticks) / ((double)TimeSpan.TicksPerMillisecond)).ToString());
Debug.Print(" Source string : " + source);
Debug.Print(" Dest string : " + dest);
Debug.Print(" Source length : " + source.Length);
Debug.Print(" Dest length : " + dest.Length);
Debug.Print("");
}
[/Code]
And here is a dump of the StringBuilder when it’s stopped in the debugger:
sb {1======12======123======1234======12345123—1234—12345—123456—1234567—12345678—123456789—1234567890—}
Capacity 4280
Length 4280
m_ChunkChars {char[4250]}
m_ChunkLength 4250
m_ChunkOffset 30
m_ChunkPrevious {1======12======123======1234==}
m_MaxCapacity 2147483647
MaxCapacity 2147483647
And here is the exception. It seems to indicate that the MaxCapacity is insufficient, but that can’t be true??
Test 1: string replace using StringBuilder.Replace…
Free mem before : 7288344
Capacity = 4250
#### Exception System.ArgumentOutOfRangeException - CLR_E_OUT_OF_RANGE (1) ####
#### Message:
#### System.Array::Copy [IP: 0000] ####
#### System.Text.StringBuilder::ReplaceInPlaceAtChunk [IP: 0022] ####
#### System.Text.StringBuilder::ReplaceAllInChunk [IP: 0047] ####
#### System.Text.StringBuilder::Replace [IP: 00e4] ####
#### System.Text.StringBuilder::Replace [IP: 000b] ####
#### FEZCobra.WebServer.ProgramTest::Main [IP: 00bf] ####
A first chance exception of type ‘System.ArgumentOutOfRangeException’ occurred in mscorlib.dll
An unhandled exception of type ‘System.ArgumentOutOfRangeException’ occurred in mscorlib.dl