在浏览了很多网站和一些教程视频之后,我仍然对这个视频感到难过。我正在完成一个程序,我需要添加最后一点功能。
该程序以这种方式工作。用户在textbox1中指定文件,然后在textbox2中指定目录。用户通过在textbox3中复制来设置他们想要文件的频率。用户点击运行,程序将文件复制到新位置,每次复制时都会在文件名中添加一个数字(以避免覆盖)。一切正常,但我希望用户可以选择按时间或文件修改时复制文件。
如何使用FileSystemWatcher查找目录中的修改(在textbox1中给出),然后调用将指定目录复制到目标目标的语句(在文本框2中指定)? < / p>
附加说明:
在一个教程中,通过执行此操作设置了FileSystemWatcher路径
Dim watched As String = System.IO.Path.Combine(Environment.GetEnvironmentVariable("USERPROFILE"), "Pictures")
Dim fsw As New FileSystemWatcher(watched)
代码指向的路径是“C:\ Users [User Name] \ Pictures”。 我找不到在线资源,显示“.GetEnvironmentVariable”接受的变量,甚至变量的含义。这是我在使用最后一位代码时遇到问题的众多原因之一。
答案 0 :(得分:0)
GetEnvironmentVariable
返回当前进程的指定环境的值。
对于您的示例,USERPROFILE
是当前用户的文件夹的路径。例如,在我的笔记本电脑上,USERPROFILE是C:\ Users \ Tim。
System.IO.Path.Combine(Environment.GetEnvironmentVariable("USERPROFILE"), "Pictures")
的输出将是USERPROFILE路径加上“图片” - 继续我的示例,它将是C:\Users\Tim\Pictures
- 这是我的用户帐户的“我的图片”文件夹的物理路径
要获取所有环境变量的列表,如果您感到好奇,请转到DOS提示符并输入SET
并点击返回。
要回答原始问题,您需要处理FileSystemWatcher.Changed Event。
例如:
Private Shared Sub OnChanged(source As Object, e As RenamedEventArgs)
' Do your copy here
End Sub
您可以将事件处理程序挂钩到FileWatcher
,如下所示:
AddHandler fsw.Changed, AddressOf OnChanged
但是,请注意MSDN文档中的此警告。
Common file system operations might raise more than one event. For example, when a file is moved from one directory to another, several OnChanged and some OnCreated and OnDeleted events might be raised. Moving a file is a complex operation that consists of multiple simple operations, therefore raising multiple events. Likewise, some applications (for example, antivirus software) might cause additional file system events that are detected by FileSystemWatcher.
答案 1 :(得分:0)
这是我用它做的我想做的代码。
Option Explicit On
Option Strict On
Imports System.IO
Imports Microsoft.VisualBasic ' I don't know this one, but the code worked without this.
Imports System.Security.Permissions ' I don't know the exactly what this does but the
' http://msdn.microsoft.com/ site did this, I assume it'f to allow for permission to
' watch files? The code still worked for me without this
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Me.Load
Dim directoryPath As String = Path.GetDirectoryName(TextBox1.Text)
Dim varFileSystemWatcher As New FileSystemWatcher()
varFileSystemWatcher.Path = directoryPath
varFileSystemWatcher.NotifyFilter = (NotifyFilters.LastWrite)
varFileSystemWatcher.Filter = Path.GetFileName(TextBox1.Text) ' I know this
' limits what's being watched to one file, but right now this is
' what I want the program to do.
AddHandler varFileSystemWatcher.Changed, AddressOf OnChanged
varFileSystemWatcher.EnableRaisingEvents = True
End Sub
Private Sub OnChanged(source As Object, ByVal e As FileSystemEventArgs)
My.Computer.FileSystem.CopyFile(e.FullPath, TextBox2.Text & "\" & e.Name, True)
End Sub