从快捷方式启动时,程序不会删除文件

时间:2014-03-15 18:37:56

标签: .net vb.net io

我有一个小问题,后果很严重。 每当我从快捷方式启动我的应用程序时,它都会说该文件已存在于该位置。我正在使用的代码是:

Dim myfile As String = "HyperCredit.exe"

If System.IO.File.Exists(myfile) = True Then
    Dim fi As New FileInfo(myfile)
    fi.Delete()
End If

My.Computer.Network.DownloadFile("http://hypercredit.co.uk/HyperCredit.exe", "C:\Program Files\HyperCredit\HyperCredit.exe")
Shell("HyperCredit.exe")

Me.Close()

正如您所看到的,这不应该发生,因为它会删除文件然后下载它。 奇怪的是,当我从exe启动应用程序时,它的工作正常,这只有在我从快捷方式启动它时才会发生

有人可以帮帮我吗? 感谢

编辑:我得到这个错误mydirectory没有声明,由于它的prptection级别可能无法访问

Dim myfile As String = "HyperCredit.exe"

If System.IO.File.Exists(myfile) = True Then
    Dim fi As New FileInfo(myfile)
    fi.Delete()
End If

Dim pf As System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location))

My.Computer.Network.DownloadFile("http://hypercredit.co.uk/HyperCredit.exe", pf & "\HyperCredit.exe")
Shell("HyperCredit.exe")

Me.Close()

1 个答案:

答案 0 :(得分:1)

我看到它的方式,文件实际上是从应用程序的工作目录中存在而不是,这可能与您的代码在尝试下载时所假设的非常不同。

假设WD在C:\ Program Files中是错误的。例如,在64位计算机上,如果您的应用程序是32位应用程序,那么该路径很可能是程序文件(x32)。另外,如果系统安装在D:而不是C:?

,该怎么办?

您应该使用System.IO.Directory.GetCurrentDirectory()动态检索应用程序的工作目录,然后将其用作文件根目录。

修改

您可能想要使用此代码:

System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location))

无论任何快捷方式的工作目录如何,这都将为您提供可执行程序集。可能你会喜欢它。

以下代码应如何显示:

Dim myfile As String = "HyperCredit.exe"
Dim myDirectory As String = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location))
Dim myFullPath As String = System.IO.Path.Combine(myDirectory, myFile)

If System.IO.File.Exists(myFullPath) Then
    System.IO.File.Delete(myFullPath)
End If

My.Computer.Network.DownloadFile("http://hypercredit.co.uk/HyperCredit.exe", myFullPath)

Shell(myFullPath)