Search code examples
vb.netwindowsioappdata

Visual Basic - Stuck trying to delete data in AppData


I wanted to make a Visual Basic application to delete the following file but I'm new to VB, sorry!:

C:\Users\username\AppData\Local\Google\Chrome\User Data\Default\Cookies

The file appears to not have a file extension, but it is an SQL-type file. I'm having a problem trying to use the "username" variable. I have tried things like %USER% in that space, but it keeps giving me an error about not being able to find the file. If anyone can spot any errors in the the following code I assigned to a button I would be very grateful:

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim FileToDelete As String

    FileToDelete = "C:\Users\%USERNAME%\AppData\Local\Google\Chrome\User Data\Default\Cookies"

    If System.IO.File.Exists(FileToDelete) = True Then

        System.IO.File.Delete(FileToDelete)
        MsgBox("File Deleted")

Solution

  • In vb.net you have the ability to use the Enviroment.GetFolderPath() method. To get where you want the code would be:

    Dim appData As String = GetFolderPath(SpecialFolder.LocalApplicationData)
    

    SpecialFolder is an Enumeration that allows you to select from many different folders such as Program Files or Desktop. To read more about the Environment.SpecialFolder enum please visit: https://msdn.microsoft.com/en-us/library/system.environment.specialfolder%28v=vs.110%29.aspx

    This will get you the local appdata folder (I assume that is the one you want from the path you gave us.

    Once you use the above string it is as simple as concatenating the variable into your string like so:

    FileToDelete = appData & "\Google\Chrome\User Data\Default\Cookies"
    

    Keep in mind you would also need

    Imports System.Environment
    

    At the start of your code.