Create Shortcut in StartUp folder (VB.NET) - vb.net

I have this code and it's giving troubles:
Imports IWshRuntimeLibrary
Imports Shell32
Public Sub CreateShortcutInStartUp(ByVal Descrip As String)
Dim WshShell As WshShell = New WshShell()
Dim ShortcutPath As String = Environment.GetFolderPath(Environment.SpecialFolder.Startup)
Dim Shortcut As IWshShortcut = CType(WshShell.CreateShortcut(ShortcutPath &
Application.ProductName & ".lnk"), IWshShortcut)
Shortcut.TargetPath = Application.ExecutablePath
Shortcut.WorkingDirectory = Application.StartupPath
Shortcut.Descripcion = Descrip
Shortcut.Save()
End Sub
According to what I have read, this is how you create a shortcut in Startup. But, no matter how much I call this Sub, shortcut does not show up. I ALREADY look up to a lot of similar questions around S.O and various other sites.
I even tried to create the shortcut from other application and still doesn't show up as expected.
What am I missing?

You have two errors in your code:
1) The path isn't being concatenated properly so change this:
Dim Shortcut As IWshShortcut = CType(WshShell.CreateShortcut(ShortcutPath & Application.ProductName & ".lnk"), IWshShortcut)
to this:
Dim Shortcut As IWshShortcut = CType(WshShell.CreateShortcut(System.IO.Path.Combine(ShortcutPath, Application.ProductName) & ".lnk"), IWshShortcut)
2) You spelled Description wrong so change:
Shortcut.Descripcion = Descrip
to this:
Shortcut.Description = Descrip
Here is the fixed subroutine:
Public Sub CreateShortcutInStartUp(ByVal Descrip As String)
Dim WshShell As WshShell = New WshShell()
Dim ShortcutPath As String = Environment.GetFolderPath(Environment.SpecialFolder.Startup)
Dim Shortcut As IWshShortcut = CType(WshShell.CreateShortcut(System.IO.Path.Combine(ShortcutPath, Application.ProductName) & ".lnk"), IWshShortcut)
Shortcut.TargetPath = Application.ExecutablePath
Shortcut.WorkingDirectory = Application.StartupPath
Shortcut.Description = Descrip
Shortcut.Save()
End Sub

Imports Microsoft.Win32 and
Imports IWshRuntimeLibrary
TO CREATE A SHORTCUT
Private Sub btnCreateShortcut_Click_(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCreateShortcut.Click
'To create Start shortcut in the windows Startup folder:
Dim WshShell As WshShell = New WshShell
Dim SRT As String = Environment.GetFolderPath(Environment.SpecialFolder.Startup)
'Fixing the Shortcut Location instead of StartupScreenLocker
'Name your Shortcut, Example \ScreenLocker.Ink
Dim ShortcutPath As String = SRT & "\ScreenLocker.lnk"
'Add shortcut.
Dim Shortcut As IWshRuntimeLibrary.IWshShortcut
Shortcut = CType(WshShell.CreateShortcut(ShortcutPath), IWshRuntimeLibrary.IWshShortcut)
Shortcut.TargetPath = Application.ExecutablePath
Shortcut.WorkingDirectory = Application.StartupPath
Shortcut.Save()
End Sub
TO DELETE THE SHORTCUT
Private Sub btnDeleteShortcut_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDeleteShortcut.Click
'To create Start shortcut in the windows Startup folder:
Dim Shortcut As String = Environment.GetFolderPath(Environment.SpecialFolder.Startup)
'Name the Shortcut you want to delete, Example \ScreenLocker.Ink
Dim ShortcutPath As String = Shortcut & "\ScreenLocker.lnk"
'To delete the shortcut:
If IO.File.Exists(ShortcutPath) Then
IO.File.Delete(ShortcutPath)
End If
End Sub

Related

Copy files with multiple search criteria

I'm trying to copy files in a directory into a new folder. The script works on one file type, but I have 6 types I need to search for. I thought I could use a bar ("|") like you can with a Regex but that didn't work. Then I tried using an array and had no luck there.
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnMove.Click
Dim sourceDir As String
sourceDir = txtMovePath.Text
Dim foundFile As Object = Nothing
Dim graphicsFldr As String
graphicsFldr = sourceDir + "\Graphics\"
For Each foundFile In My.Computer.FileSystem.GetFiles(sourceDir, _
Microsoft.VisualBasic.FileIO.SearchOption.SearchTopLevelOnly, _
"*.cgm|*.eps|*.svg|*.wmf|*.jpg|*.png|*.iso")
My.Computer.FileSystem.CopyFile(foundFile, graphicsFldr & My.Computer.FileSystem.GetName(foundFile))
Next
End Sub
End Class
Module mainModule
Sub Main()
Form1.Show()
End Sub
Use this
Dim arr = {"*cgm","*.eps","*.svg","*.wmf","*.jpg","*.png","*.iso"}
For Each foundFile In My.Computer.FileSystem.GetFiles(sourceDir, _
Microsoft.VisualBasic.FileIO.SearchOption.SearchTopLevelOnly, arr)
My.Computer.FileSystem.CopyFile(foundFile, graphicsFldr & My.Computer.FileSystem.GetName(foundFile))
Next

Getting CommandLineArgs StartsWith Failing

I've got an application. I haven't had to use command line arguments before but my research suggests my method isn't wrong. In VS2015, in my project properties->debug I've added /boxID=123 but when I debug, I get nothing in my inputVal variable. Where am I going wrong?
Imports Word = Microsoft.Office.Interop.Word 'needed for COM object interaction with MS Word
Imports System.Data.SqlClient 'needed for DB interactions
Imports System.IO 'needed for BLOB
Public Class Window
'set form level declarations
Dim appPath As String
Dim objWordApp As New Word.Application
Dim objDoc As Word.Document
Function boxIDfromCommandLine() As Integer
Dim inputArg As String = "/boxID="
Dim inputVal As String = ""
For Each s As String In My.Application.CommandLineArgs
If s.ToLower.StartsWith(inputArg) Then
inputVal = s.Remove(0, inputArg.Length)
End If
Next
If inputVal = "" Then
inputVal = "0"
End If
boxIDfromCommandLine = Convert.ToInt32(inputVal)
End Function
'form load subroutine
Private Sub Window_Load(ByVal sender As System.Object, e As System.EventArgs) Handles MyBase.Load
'Establish application path, replace appPath on deployment
Dim appPath As String = Application.StartupPath()
'Run application in foreground or background.
'If in background (false), be sure to add objDoc.close() and objWordApp.Quit()
objWordApp.Visible = False
'Declarations
Dim localDateTimeString As String = DateTime.Now.ToString
Dim localDateTimeFileName As String = DateTime.Now.ToString("yyyyMMddhhmm")
Dim soNumber As String = "No_SO_Selected"
Dim boxID As Integer = boxIDfromCommandLine()
Dim saveString As String 'file name format
Dim savePath As String = "C:\ITO_PackingLists" 'set folder location
Dim connection As SqlConnection = New SqlConnection() 'set SQL server connection string
...
...
...

vb.net Creating folders for each files in the listbox

listbox1 lists sub-folders that contain files.
listbox2 has files list.
When button1 is pressed I hope the folders are made for each files in the listbox2(folder name should be as same as file name) and then move corresponding file to that directory.
eg)
listbox1
d:\data\sub1\
listbox2
d:\data\sub1\a.7z
d:\data\sub1\ab.7z
when button1 is pushed
we can find the files in...
d:\data\sub1\a\a.7z
d:\data\sub1\ab\a.7z
I'm having trouble to make it. I know how to list files in the listbox but I don't know how to deal with each of them.
Also, if I try to get rid of 7z extension in the directory name with the following code, it says it can not be used for the listbox.
If folderslist.SelectedItem IsNot Nothing Then
' selected item is filepath
Dim filePath = folderslist.SelectedItem.ToString
The string you are searching
Dim s As String = filePath
Find index of uppercase letter 'B'
Dim i As String = 0
Dim j As String = s.IndexOf("."c)
This new string contains the substring starting at B
part = s.Substring(i, j - i + 1)
If (s.IndexOf(".") = -1) Then
part = "Not found"
End If
Any advice, please.
You don't need to manually split the path to get separate strings. Use
System.IO.Path.GetFileName, and
System.IO.Path.GetFileNameWithoutExtension and
System.IO.Path.GetDirectoryName.
And the like.
It's a little difficult to give a direct, explicit example, because it's quite unclear what you want to do based on what you're shown. But as an example...
Dim basePath as String = "d:\data\sub1\"
Dim fullName as String = folderslist.SelectedItem.ToString()
Dim fileName as String = Path.GetFileName(fullName)
Dim partialName as String = Path.GetFileNameWithoutExtension(fullName)
Dim newPath as String = Path.Combine(basePath, partialName)
newPath = newPath + Path.Combine(newPath, fileName)
Private Sub Timer2_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer2.Tick
If folderslist.SelectedItem IsNot Nothing Then
Dim filePath = folderslist.SelectedItem.ToString
fileslist.Items.Clear()
Dim dirf As String() = Directory.GetFiles(filePath, "*.7z")
Dim dira As String
For Each dira In dirf
fileslist.Items.Add(dira)
Next
If mkfold = 1 Then
For Each dira In dirf
Dim pName As String = Path.GetFileNameWithoutExtension(dira)
Dim strDir As String
strDir = filePath & "\" & pName
If DirExists(Trim(strDir)) = False Then
MkDir(Trim(strDir))
End If
Dim f_name As String = Path.GetFileName(dira)
My.Computer.FileSystem.MoveFile(dira, strDir & "\" & f_name)
Next
mkfold = 0
End If
End If
Private Sub mkfol_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mkfol.Click
mkfold = 1
End Sub
Somehow I got what I wanted.

Deleting Specific Files in VB.NET

I am trying to figure out the code on Visual Basic after I have already extracted all files from a folder that was in a flash drive and put them in a folder on the computer. How could I have this program delete all the files that have not been modified from a previous date in the folder on the computer?
This is what I have so far:
Imports System.IO
Public Class frmExtractionator
Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
Dim sourceDirectory As String = "E:\CopierFolderforTestDriveCapstone"
Dim archiveDirectory As String = "E:\FilesExtracted"
Try
Dim txtFiles = Directory.EnumerateFiles(sourceDirectory)
If(Not System.IO.Directory.Exists(archiveDirectory )) Then
System.IO.Directory.CreateDirectory(archiveDirectory)
End If
For Each currentFile As String In txtFiles
Dim fileName = currentFile.Substring(sourceDirectory.Length + 1)
File.Move(currentFile, Path.Combine(archiveDirectory, fileName))
Next
Catch eT As Exception
Console.WriteLine(eT.Message)
End Try
End Sub
End Class
Something like this will delete files that have not been modified since the given date.
Private Sub DeleteUnmodifiedFiles(directoryName As String, modificationThreshold As Date)
Dim folder As New DirectoryInfo(directoryName)
Dim wasModifiedSinceThreshold As Boolean
For Each file As FileInfo In folder.GetFiles
wasModifiedSinceThreshold = (file.LastWriteTime > modificationThreshold)
If (Not wasModifiedSinceThreshold) Then file.Delete()
Next
End Sub
To delete based on a number of days...
Private Sub DeleteUnmodifiedFiles(directoryName As String, modificationThresholdDays As Integer)
Dim folder As New DirectoryInfo(directoryName)
Dim thresholdDate As Date
Dim wasModifiedSinceThreshold As Boolean
For Each file As FileInfo In folder.GetFiles
thresholdDate = DateTime.Now().AddDays(-1 * modificationThresholdDays)
wasModifiedSinceThreshold = (file.LastWriteTime > thresholdDate)
If (Not wasModifiedSinceThreshold) Then file.Delete()
Next
End Sub

VB.NET / C# code to access target path of link (lnk) files produces some wrong paths

I found this code:
Public Shared Function GetLnkTarget(ByVal lnkPath As String) As String
Dim shl = New Shell32.Shell()
' Move this to class scope
lnkPath = System.IO.Path.GetFullPath(lnkPath)
Dim dir = shl.[NameSpace](System.IO.Path.GetDirectoryName(lnkPath))
Dim itm = dir.Items().Item(System.IO.Path.GetFileName(lnkPath))
Dim lnk = DirectCast(itm.GetLink, Shell32.ShellLinkObject)
Return lnk.Target.Path
End Function
It works for some .lnk files, but for example if I add my Skype.exe desktop link it produces:
C:\Windows\Installer\{...}\SkypeIcon.exe
Is there a fix for this?
Try this:
Function GetTargetPath(ByVal FileName As String)
Dim Obj As Object
Obj = CreateObject("WScript.Shell")
Dim Shortcut As Object
Shortcut = Obj.CreateShortcut(FileName)
GetTargetPath = Shortcut.TargetPath
End Function
Private Sub Teste_Load(sender As Object, e As EventArgs) Handles MyBase.Load
MsgBox(GetTargetPath("C:\ProgramData\Microsoft\Windows\Start Menu\BitTorrent.lnk"))
'here you chose the location of .lnk file
End Sub
CreateShortcut() doesn't work as expected with certain shortcuts that have a greyed out target in the properties, like Adobe Reader and Microsoft Word. The targetpath ends up being something under c:\windows\installer (icon?).