Click here to Skip to main content
15,891,248 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
So, this is my code:
My.Computer.FileSystem.RenameFile("C:\j\WindowsApplication1.exe", String.Format("{0}.exe", Path.GetRandomFileName().Replace(".", String.Empty)))
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.
Posted
Updated 16-Jul-17 6:10am
v2

Try:
VB
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
 
Share this answer
 
Comments
[no name] 16-Jul-17 13:59pm    
Thanks for help and reply! :)
OriginalGriff 16-Jul-17 14:29pm    
You're welcome!
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.
 
Share this answer
 
Comments
[no name] 16-Jul-17 13:50pm    
Hey, I don't understand where I should insert If File.Exists(fileName), can you give me your source in my source? Because I get errors
Atlapure Ambrish 17-Jul-17 6:38am    
If File.Exists("C:\j\WindowsApplication1.exe")
{
My.Computer.FileSystem.RenameFile("C:\j\WindowsApplication1.exe",
String.Format("{0}.exe", Path.GetRandomFileName().Replace(".", String.Empty)))
}
[no name] 16-Jul-17 13:59pm    
Thanks for help and reply! :)
Atlapure Ambrish 17-Jul-17 6:45am    
You welcome!

Please don't down vote the answer, if you don't understand do ask questions.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900