首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在后台备份文档

问在后台备份文档
EN

Stack Overflow用户
提问于 2014-05-24 00:11:29
回答 1查看 234关注 0票数 0

我知道如何为word创建一个在后台自动保存文档的vs2013插件:

代码语言:javascript
复制
this.Application.Documents[@"C:\Test\NewDocument.docx"].Save();

这样做的问题是,如果用户将文档保存到:

C:\MyDocument.docx,并且没有意识到位置在后台已更改为C:\Test\NewDocument.docx,他们可能会感到困惑。

所以我的问题是,有没有可能以某种方式在后台在不同的位置创建文档的备份?因此,插件会自动保存到C:\Test\NewDocument.docx,但当用户单击Word中的内置保存功能时,它也会保存到用户认为应该保存的位置。

这个是可能的吗?

EN

回答 1

Stack Overflow用户

发布于 2014-05-24 04:36:59

让我们先弄清楚你在做什么

你的

代码语言:javascript
复制
this.Application.Documents[@"C:\Test\NewDocument.docx"].Save();

不是任何在后台保存文件的魔法。它只是将文档保存到具有特定名称{NewDocument.docx)的特定路径(C:\Test)中。因此,您只需保存文档,而不保存其他内容。

如果您想复制现有文档,但又不想强制用户保存它,您有两个选择

Word中

  1. 自动保存功能(我不知道如何通过代码控制)
  2. 复制现有文件,该文件必须至少保存一次

让我们来谈谈#2,你可以很容易地将一个文件从一个位置复制到另一个位置,但是这个文件必须关闭。所以还有另一种方法,下面是一个函数示例(我不喜欢直接访问全局变量,但对于这个示例来说是可以的)

代码语言:javascript
复制
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

结束类

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23833935

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档