Search code examples
c#office-interop

Word Interop Disable Overwriting While Saving


I am trying to export some text from RichTextBox to a word application. I got things figured out for the most part, but I cannot figure how to disable the overwrite feature if the filename is the same. I found a couple of posts where they wanted to enable the overwrite while saving without prompting the user, but trying the opposite of those solution didn't resolve :( I would like to code in such a way so that the Word would prompt users if there already is a file with a given filename.

The code snippet is below

 private void BtnExportToWord_Click(object sender, EventArgs e)
    {
        string fileName = "abc123";
        FolderBrowserDialog folderBrowser = new FolderBrowserDialog();
        folderBrowser.ShowDialog();
        string folderLocation = folderBrowser.SelectedPath;
        string fileNameWithPath = string.Format("{0}\\{1}", folderLocation, fileName );
        string rtf = fileNameWithPath + ".rtf";
        string doc = fileNameWithPath + ".doc";

        richTextBox1.SaveFile(rtf);
        var wordApp = new Word.Application();

        /* none of these modes help
        wordApp.DisplayAlerts = Word.WdAlertLevel.wdAlertsAll;
        wordApp.DisplayAlerts = Word.WdAlertLevel.wdAlertsMessageBox; */

        var document = wordApp.Documents.Open(rtf);
        document.SaveAs(doc, Word.WdSaveFormat.wdFormatDocument);
        document.Close();
        wordApp.Quit();
        File.Delete(rtf); 
    }

What is it that I am missing here?

ps. Similar post: disabling overwrite existing file prompt in Microsoft office interop FileSaveAs method The answer there shows that DisplayAlert is a bool, but my VS Intellisense shows it takes an enum of type WdAlertLevel. How come my doesn't prompt by default? Different Versions?


Solution

  • Use a SaveFileDialog() to prompt where they'd like to save the "doc" file. If the "doc" file already exists, just keep prompting them.

    string docFilePath;
    
    using (var sfd = new SaveFileDialog())
    {
        sfd.InitialDirectory =
            Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
        sfd.FileName = fileName + ".doc";
    
        while (true)
        {
            sfd.ShowDialog();
    
            if (!File.Exists(sfd.FileName))
            {
                docFilePath = sfd.FileName;
                break;
            }
        }
    }
    

    Once you've got the path where'd they'd like to save the "doc" file, just strip the file path out, save your "rtf" file, then the "doc" file, and delete the "rtf" file.

    var rtfFilePath = Path.Combine(
        Path.GetFullPath(docFilePath), Path.GetFileNameWithoutExtension(docFilePath), ".rtf");
    

    I'm guessing at some of the settings here, like for InitialDirectory. You'll have to play around with it to get it just how you want.