简体   繁体   中英

Toggle Renaming a File without checking if it exists in VB.Net

Non programmer trying to toggle renaming a file from a vb.net form without checking if it exists. Have done this with simple batch file. Would like to to know if it is possible in vb.net without needing to check if file exists. Also do not want to use toggle control, want to use button control as UI preference. Code used in batch file:

set ADDON_PATH="P:\MyPath\MySubFolder\"
set ADDON_NAME="myfile.dll"
set DISABLE_NAME="myfile.bak"
cd /d %ADDON_PATH%
Ren %ADDON_NAME% %DISABLE_NAME% 2> nul || ren %DISABLE_NAME% %ADDON_NAME% 2> nul

Partial code here for vb.net using button, not toggle button

Private Sub PlayVanilla(sender As Object, e As EventArgs) Handles Button11.Click
        If Button11.Text = "Vanilla Mode" Then
            Button11.Text = "Modded Game"
            Button11.ForeColor = Color.Green
            My.Computer.FileSystem.RenameFile("P:\MyPath\MySubFolder\myfile.dll", "myfile.bak")
        Else
            Button11.Text = "Vanilla Mode"
            Button11.ForeColor = Color.Red
            My.Computer.FileSystem.RenameFile("P:\MyPath\MySubFolder\myfile.bak", "myfile.dll")
        End If

    End Sub
 

I haven't tried the code above because obviously the file could be in either state, myfile.bak or myfile.dll. So the question is, do i need to check if file exists or can I use a construct as I did in the batch file. One final note, this file always exists and I'm the only user so 0% risk of it not being there. The batch file works simply and perfectly but I don't want to run the batch file from VB form, looking for VB solution. Thank you.

Unable to find solution matching the batch file example, so will test for file exists. In passing, this isn't an enterprise solution -probability of the file being locked by another process is exactly zero. Additionally, there is 100% probability the file exists in one of two name states. However I understand and appreciate the robustness comments and accept them. Thanks. Imports system.io

If Directory.Exists("P:\MyPath\Myfolder\Myfile.dll") Then

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM