如果文件不存在,让代码停止尝试? [英] Make code stop trying if file doesn't exist?

查看:60
本文介绍了如果文件不存在,让代码停止尝试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,这是我的代码:

My.Computer.FileSystem.RenameFile("C:\j\WindowsApplication1.exe", String.Format("{0}.exe", Path.GetRandomFileName().Replace(".", String.Empty)))

我用Form_Load编写的。此代码为我的应用程序提供随机文件名。当我打开应用程序时,我收到错误。发生此错误是因为我的应用程序一直在尝试重命名该文件,但由于文件名已更改为随机名称,因此无法找到该文件。如果路径不存在,如何让文件停止尝试重命名文件?



我尝试过:



我试过用计时器解决这个问题,它在第一次打开应用程序时起作用。但是,当我第二次打开应用程序时,我收到一条错误消息,因为文件的名称已更改,因此无法找到文件路径。

which I have written in Form_Load. This code gives my application a random filename. When I open the application I get an error. The error occurs because my application keeps trying to rename the file, but can't find it since the filename has changed to a random name. How can I make the file stop trying to rename the file if the path doesn't exist?

What I have tried:

I have tried solving this with a timer, it works when I open the application the first time. But, when I open the application the second time, I get an error message because the file's name has changed, so it can't find the file path.

推荐答案

尝试:

Try:
Dim newName As String = String.Format("{0}.exe", Path.GetRandomFileName().Replace(".", ""))
Dim oldName As String = "C:\j\WindowsApplication1.exe"
If File.Exists(oldName) Then
	File.Move(oldName, newName)
End If


正如您所提到的,我假设您的代码按预期工作,问题只是即使路径确实存在,它仍在尝试重命名。考虑到这一点,只需在重命名前添加以下检查。



如果File.Exists(fileName)



将您的代码包含在此if条件中。
As you mentioned, I assume your code is working as expected, the problem is just that it is still trying to rename even if path does exists. Considering this, just add the below check before rename.

If File.Exists(fileName)

enclose your code in this if condition.


这篇关于如果文件不存在,让代码停止尝试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆