{"record":{"id":"969bd1b518b99e83","repo":"dotnet/wpf","slug":"sr-filenamemustnotbenull-savefiledialog","errorCode":null,"errorMessage":"SR.FileNameMustNotBeNull","messagePattern":"SR\\.FileNameMustNotBeNull","errorType":"exception","errorClass":"InvalidOperationException","httpStatus":null,"severity":"error","filePath":"src/Microsoft.DotNet.Wpf/src/PresentationFramework/Microsoft/Win32/SaveFileDialog.cs","lineNumber":72,"sourceCode":"        /// <summary>\n        ///  Opens the file selected by the user with read-only permission.  \n        /// </summary>\n        ///  The filename used to open the file is the first element of the\n        ///  FileNamesInternal array.\n        /// <exception cref=\"System.InvalidOperationException\">\n        /// Thrown if there are no filenames stored in the SaveFileDialog.\n        /// </exception>\n        public Stream OpenFile()\n        {\n\n            // Extract the first filename from the ItemNames list.\n            string filename = CriticalItemName;\n\n            // If we got an empty or null filename, throw an exception to\n            // tell the user we don't have any files to open.\n            if (string.IsNullOrEmpty(filename))\n            {\n                throw new InvalidOperationException(SR.FileNameMustNotBeNull);\n            }\n\n            // Create a new FileStream from the file and return it.\n            return new FileStream(filename, FileMode.Create, FileAccess.ReadWrite);\n        }\n\n        //\n        //   We override the FileDialog implementation to set a default\n        //   for FOS_FILEMUSTEXIST in addition to the other option flags\n        //   defined in FileDialog.\n        /// <summary>\n        ///  Resets all properties to their default values.\n        /// </summary>\n        public override void Reset()\n        {\n\n            // it is VERY important that the base.reset() call remain here\n            // and be located at the top of this function.","sourceCodeStart":54,"sourceCodeEnd":90,"githubUrl":"https://github.com/dotnet/wpf/blob/81131a70a4c573cd62748a5c36908fc4d662daa9/src/Microsoft.DotNet.Wpf/src/PresentationFramework/Microsoft/Win32/SaveFileDialog.cs#L54-L90","documentation":"SaveFileDialog.OpenFile creates a stream for the file the user chose to save to. If CriticalItemName (the chosen filename) is null or empty — meaning the dialog never completed successfully — an InvalidOperationException is thrown instead of attempting to create a file from an invalid name.","triggerScenarios":"Calling OpenFile() without calling ShowDialog or after the user cancelled the dialog; using a newly constructed SaveFileDialog that was never shown; Clearing the dialog state then calling OpenFile.","commonSituations":"Forgetting to check the nullable result of ShowDialog before opening the save stream; calling OpenFile in a finally/cleanup block that runs on cancellation; constructing the dialog on the fly for unit tests without showing it.","solutions":["Call ShowDialog() and proceed to OpenFile() only when it returned true","Guard with !string.IsNullOrEmpty(dlg.FileName) before calling OpenFile","Treat dialog cancellation as a normal flow branch, not an exception case","For programmatic saves without user interaction, use File.Create/FileStream directly instead of SaveFileDialog"],"exampleFix":"// before\nvar dlg = new SaveFileDialog();\nusing var s = dlg.OpenFile();\n// after\nvar dlg = new SaveFileDialog();\nif (dlg.ShowDialog() == true)\n{\n    using var s = dlg.OpenFile();\n}","handlingStrategy":"validation","validationCode":"if (dlg.ShowDialog() != true || string.IsNullOrEmpty(dlg.FileName))\n    return; // cancelled or invalid\nusing var s = dlg.OpenFile();","typeGuard":"bool HasSaveTarget(SaveFileDialog d) => d.ShowDialog() == true && !string.IsNullOrEmpty(d.FileName);","tryCatchPattern":"try { using var s = dlg.OpenFile(); }\ncatch (InvalidOperationException ex) when (ex.Message.Contains(\"null\"))\n{\n    // user cancelled; no save target\n}","preventionTips":["Check ShowDialog()==true before OpenFile","Skip save logic on cancellation instead of routing it through OpenFile","Use direct FileStream when saving programmatically without a dialog"],"tags":["wpf","savefiledialog","null","filename"],"backgroundTag":"null-argument","analyzedSha":"81131a70a4c573cd62748a5c36908fc4d662daa9","analyzedAt":"2026-09-14T10:12:48.479Z","contentChangedAt":"2026-09-14T10:12:48.479Z","schemaVersion":2},"datasetVersion":"2026-09-21T21:30:21.729Z"}