我知道如何创建一个vs2013插件,用于自动在后台保存文档:
this.Application.Documents[@"C:\Test\NewDocument.docx"].Save();
问题在于,如果用户将文档保存到:
C:\MyDocument.docx
并且没有意识到该位置在后台更改为C:\Test\NewDocument.docx
,他们可能会感到困惑。
所以我的问题是,是否有可能以某种方式在后台创建一个不同位置的文档备份?因此,addin会自动保存到C:\Test\NewDocument.docx
,但是当用户单击Word中的内置保存功能时,它会保存到用户认为应该保存的位置。
这可能吗?
答案 0 :(得分:0)
让我们先说清楚你在做什么
您
this.Application.Documents[@"C:\Test\NewDocument.docx"].Save();
不是任何在后台保存文件的魔法。它只是将文档保存到具有特定名称{NewDocument.docx)的特定路径(C:\ Test)中。所以你只需保存文档,没有别的。
如果您想复制现有文档并且不想强制用户保存它,您有两个选择
让我们谈谈#2,您可以轻松地将文件从一个位置复制到另一个位置,但必须关闭该文件。所以还有另一种方法,功能性示例如下(我不喜欢直接访问Globals但是这个例子没问题)
Public Class ThisAddIn
Dim _myTimer As System.Windows.Forms.Timer
Private Sub ThisAddIn_Startup() Handles Me.Startup
_myTimer = New System.Windows.Forms.Timer
With _myTimer
.Interval = 30000 ' 30 sec
AddHandler .Tick, AddressOf TimerEventOcured
.Start()
End With
End Sub
Private Sub ThisAddIn_Shutdown() Handles Me.Shutdown
If _myTimer IsNot Nothing Then _myTimer.Stop()
End Sub
Private Sub TimerEventOcured(ByVal sender As Object, ByVal e As EventArgs)
CopyFile()
End Sub
Private Sub CopyFile()
Const DEST_PATH As String = "c:\"
Const FILE_NAME As String = "BackUp.docx"
Try
Dim currentDoc As Word.Document = Globals.ThisAddIn.Application.ActiveDocument
' was it saved at least once, the full path then contains extension, e.g. dotx
If Not currentDoc.FullName.Contains(".") Then Return
' makes copy of the current document with UNSAVED changes and save it to specified location
Dim backUpCopy As Word.Document = currentDoc.Application.Documents.Add(currentDoc.FullName)
Dim tmpFileNAme As String = System.IO.Path.GetTempFileName.Replace(".tmp", ".dotx")
backUpCopy.SaveAs2(FileName:=tmpFileNAme, AddToRecentFiles:=False)
System.IO.File.Copy(sourceFileName:=tmpFileNAme, _
destFileName:=Path.Combine(DEST_PATH, FILE_NAME), _
overwrite:=True)
' remove the temp files
backUpCopy.Close(SaveChanges:=False)
System.IO.File.Delete(tmpFileNAme)
System.IO.File.Delete(tmpFileNAme.Replace(".dotx", ".tmp"))
Catch ex As Exception
System.Windows.Forms.MessageBox.Show(String.Format("hey, an error here{0} {1}", vbNewLine, ex.Message))
End Try
End Sub
结束班