【问题标题】:Word Interop Disable Overwriting While Saving保存时 Word 互操作禁用覆盖
【发布时间】:2014-09-29 23:09:41
【问题描述】:

我正在尝试将一些文本从 RichTextBox 导出到 Word 应用程序。我大部分都弄清楚了,但是如果文件名相同,我不知道如何禁用覆盖功能。我发现了一些帖子,他们希望在不提示用户的情况下在保存时启用覆盖,但是尝试与这些解决方案相反的解决方案并没有解决:(我想以这样的方式编码,以便 Word 会提示用户如果已经有一个具有给定文件名的文件。

代码sn-p在下面

 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); 
    }

我在这里缺少什么?

ps。类似帖子:disabling overwrite existing file prompt in Microsoft office interop FileSaveAs method 那里的答案显示 DisplayAlert 是一个布尔值,但我的 VS Intellisense 显示它需要一个 WdAlertLevel 类型的枚举。为什么我的默认不提示?不同的版本?

【问题讨论】:

    标签: c# office-interop


    【解决方案1】:

    使用SaveFileDialog() 提示他们要将“doc”文件保存在何处。如果“doc”文件已经存在,继续提示即可。

    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;
            }
        }
    }
    

    一旦你有了他们想要保存“doc”文件的路径,只需去掉文件路径,保存你的“rtf”文件,然后是“doc”文件,然后删除“ rtf”文件。

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

    我猜这里有一些设置,比如InitialDirectory。你必须玩弄它才能得到你想要的。

    【讨论】:

    • 谢谢。这有效,但不完全是我想要的。由于我在将 rtf 文件转换为 Word doc 后将其删除,因此在下一轮将不会被识别为重复文件。你能想到的任何其他方法吗?我想我可能需要 Word Interop 方面的一些东西。
    • 不,不涉及任何与数据库相关的操作。问题是我只删除了带有 rtf 扩展名的文件,但在删除该 rtf 文件之前,我制作了一个具有相同名称的 .doc 扩展名的 Word 版本,并且这个 word 版本没有被删除。所以在下一轮,即使我使用SaveFileDialogue,也不会有任何重复文件,但是现在当我转换rtf并保存一个新的Word doc时,它会覆盖之前的word文档,因为文件名相同。这就是我要防止的。
    • 感谢您的跟进!我会试一试,看看这是否对我的情况有帮助。
    • 在开始转换为 Word 之前,我刚刚添加了一个 File.Exists 检查扩展名为 .doc 的文件。 @GrantWinney 感谢您的想法,它有帮助!赞赏。
    猜你喜欢
    • 1970-01-01
    • 2011-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-25
    • 2011-03-22
    • 1970-01-01
    相关资源
    最近更新 更多