我正在尝试将一些文本从RichTextBox导出到word应用程序。我找到了大部分内容,但如果文件名相同,我无法弄清楚如何禁用覆盖功能。我找到了几个帖子,他们希望在保存而不提示用户的情况下启用覆盖,但尝试相反的解决方案并没有解决:(我想以这样的方式编码,以便Word会提示用户,如果已经存在具有给定文件名的文件。
代码段位于
之下 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是一个bool,但是我的VS Intellisense显示它需要一个类型为WdAlertLevel的枚举。为什么默认情况下我没有提示?不同的版本?
答案 0 :(得分: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“file。
var rtfFilePath = Path.Combine(
Path.GetFullPath(docFilePath), Path.GetFileNameWithoutExtension(docFilePath), ".rtf");
我猜这里的一些设置,比如InitialDirectory
。你必须玩它才能达到你想要的效果。