/// <summary> /// Creates a new (unsaved) Document by loading it from the specified Stream, rather than a file on disk. /// </summary> /// <param name="fileName">Absolute filename of new document.</param> /// <param name="docType">Type of document to create.</param> /// <param name="stream">Stream from which to load the document's contents.</param> /// <returns></returns> public Document CreateDocument(string fileName, Type docType, Stream stream, object[] args) { // Change it to a unique (not open) name while (FindOpenDocument(fileName) != null) { string name = Path.GetFileName(fileName); int dotpos = name.IndexOf('.'); string fileBase, fileExt; if (dotpos >= 0) { fileBase = name.Substring(0, dotpos); fileExt = name.Substring(dotpos, name.Length - dotpos); } else { fileBase = name; fileExt = ""; } Regex regex = new Regex("(.*)\\[(\\d+)\\]$"); Match match = regex.Match(fileBase); if (match.Success) { int val; if (!Int32.TryParse(match.Groups[2].Value, out val)) { val = 1; } fileBase = match.Groups[1].Value + "[" + (val + 1).ToString() + "]"; } else { fileBase = fileBase + "[2]"; } fileName = Path.GetDirectoryName(fileName) + Path.DirectorySeparatorChar + fileBase + fileExt; } if (docType == null) { docType = FindDocumentType(fileName); } Document doc; try { doc = CreateAndLoadDocument(fileName, docType, stream, args); } catch (Exception ex) { DialogResult result = MessageBox.Show(MainWindow, "There was an error opening the document '" + fileName + "':\r\n\r\n" + ex.ToString() + "\r\n\r\nWould you like to try opening it as a text document?", "Error opening document", MessageBoxButtons.RetryCancel, MessageBoxIcon.Error); if (result == DialogResult.Cancel) { return(null); } else { try { stream.Seek(0, SeekOrigin.Begin); doc = CreateAndLoadDocument(fileName, FindDocumentType(".txt"), stream, null); } catch (Exception ex2) { MessageBox.Show(MainWindow, ex2.ToString(), "Error opening document:", MessageBoxButtons.OK, MessageBoxIcon.Error); return(null); } } } mOpenDocuments.Add(doc); mFileWatcher.AddFile(fileName); OnDocumentOpened(doc); return(doc); }