dotnet/wpf · error · XamlException

SR.CannotWriteClosedWriter

Error message

SR.CannotWriteClosedWriter

What it means

XamlNodeList.Add throws XamlException(SR.CannotWriteClosedWriter) when new nodes arrive after the writer has been closed and the list switched to read mode (_readMode == true). Once closed, the node list is immutable.

Solutions

  1. Create a new XamlNodeList for additional writes.
  2. Ensure no code paths write after Close() — guard writes with an isClosed flag.
  3. Restructure so the full node stream is composed before closing.

Example fix

// before
writer.Close();
writer.WriteStartObject(xamlType); // throws
// after
writer.Close();
var newList = new XamlNodeList(schemaContext);
newList.Writer.WriteStartObject(xamlType);
Defensive patterns

Strategy: validation

Validate before calling

if (!list.Writer.IsClosed) { /* safe to write */ }

Try / catch

try { writer.WriteEndObject(); }
catch (XamlException) { /* writer closed — create a new XamlNodeList */ }

Prevention

When it happens

Trigger: Calling any of the writer's Write* methods (via XamlNodeList.Writer) after Close/EOF was written, or calling Add indirectly after read mode was entered.

Common situations: Reusing a buffered XamlNodeList for a second write pass, or event/callback-driven writers that keep firing after the pipeline finished.

Understand the failure class

Background: "Invalid state transition" errors: "status must be X, actually Y", "already rejected/charging/uninstalled", "cannot ... while running" — what they mean when a library rejects your call — this error's family across 31 libraries.

Related errors


AI-assisted analysis of dotnet/wpf@81131a70a4 (2026-09-14). Data as JSON: /api/errors/a467cde55771b166. Report an issue: GitHub.

Appendix: source

Thrown at src/Microsoft.DotNet.Wpf/src/System.Xaml/System/Xaml/XamlNodeList.cs:83

        }

        private void Add(XamlNodeType nodeType, object data)
        {
            if (!_readMode)
            {
                if (nodeType != XamlNodeType.None)
                {
                    XamlNode node = new XamlNode(nodeType, data);
                    _nodeList.Add(node);
                    return;
                }

                Debug.Assert(XamlNode.IsEof_Helper(nodeType, data));
                _readMode = true;
            }
            else
            {
                throw new XamlException(SR.CannotWriteClosedWriter);
            }
        }

        private void AddLineInfo(int lineNumber, int linePosition)
        {
            if (_readMode)
            {
                throw new XamlException(SR.CannotWriteClosedWriter);
            }

            XamlNode node = new XamlNode(new LineInfo(lineNumber, linePosition));
            _nodeList.Add(node);
            if (!_hasLineInfo)
            {
                _hasLineInfo = true;
            }
        }

View on GitHub (pinned to 81131a70a4)