To avoid the error "Collection was modified after the enumerator was instantiated" I found a number of recommendations to use the following lines before looping through the Request.ServerVariables.Keys collection:
IEnumerator en = Request.ServerVariables.Keys.GetEnumerator();
en.MoveNext();
Looking at the MSDN example, they set the Server Variables to a collection, then iterate through that collection without calling GetEnumerator or MoveNext.
Two questions:
- Why do we need to call GetEnumerator and MoveNext?
- Which is the better approach if using ASP.NET and C# 4.0?