Gaining authorize Startup shortcut for All User - vb.net

When my program wanted to add a startup shortcut for All User in Win 7 (or Vista), it got an "Unauthorized Access Exception", even i login as admin.
How do get authorize access for All User in my program?
Here is the code:
Imports IWshRuntimeLibrary
Public Class Form1
Dim AppName As String = "StartUp ShortCut"
Dim startUpFolderPathALLUSERfWin7 As String = Environment.GetEnvironmentVariable(("ALLUSERSPROFILE") & "\Microsoft\Windows\Start Menu\Programs\Startup")
Private Sub Create_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim lnkPathAllUserWin7 As String = startUpFolderPathALLUSERfWin7 & "\" & AppName & ".lnk" 'need permission
Dim appPath As String = My.Computer.FileSystem.CurrentDirectory & "\" & AppName & ".exe"
Try
Dim wshs As IWshShell_Class = New IWshShell_Class
Dim shortcut As IWshShortcut_Class = TryCast(wshs.CreateShortcut(lnkPathAllUserWin7), IWshShortcut_Class)
shortcut.Description = "This is a shortcut to " & AppName
shortcut.TargetPath = appPath
shortcut.IconLocation = appPath + ",0"
shortcut.Save()
MsgBox("ShortCut File Created")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class

You need to change
Dim startUpFolderPathALLUSERfWin7 As String = Environment.GetEnvironmentVariable(("ALLUSERSPROFILE") & "\Microsoft\Windows\Start Menu\Programs\Startup")
To
Dim startUpFolderPathALLUSERfWin7 As String = Environment.GetEnvironmentVariable("ALLUSERSPROFILE") & "\Microsoft\Windows\Start Menu\Programs\Startup"
Note the difference you have the string "\Microsoft\Windows\Start Menu\Programs\Startup" added as part of the environment variable you are trying to find and was coming back as nothing, not added to the found variable. After making the change your program will write to the startup directory.

i try the above and it create a folder in my D:\, don't know why?
Anyway i found out it is the UAC that my program need to deal with (some adjustment on Application Manifest File are needed).
thanks for your help Mark.

Related

closing mdi child form causes System.ObjectDisposedException

i created a mdi database application. One child form has a datagridview. when clicking on a button on that form a new form opens with a pdfviewer(AxAcroPDF1) on it. This form shows a pdf document stored in the sql server database.
closing this form is done by Me.Close(). It closes it, but when i do it several times, opening that form and closing it, then at one point i get a
System.ObjectDisposedException which says Cannot access a disposed object and it isn't caught either in the try catch block.
It also says The application is in break mode. Your app has entered a break state, but there is no code to show because all threads where executing external code(typically system or framwork code)
Never experienced this kind of problem before.
Here is the code to launch the form with the pdf viewer
Private Sub btnShowDocument_Click(sender As Object, e As EventArgs) Handles btnShowDocument.Click
frmDocument = New frmShowDocumentatie
rowIndex = dgvData.CurrentRow.Index
FileName = dgvData.Item(6, rowIndex).Value
If FileName = "" Then
MessageBox.Show("Can't open documentation" & vbNewLine & "File doesn't exist", "Database Info", MessageBoxButtons.OK, MessageBoxIcon.Information)
Else
frmDocument.Show()
End If
End Sub
And here's the form that opens up then
Imports System.Data.SqlClient
Public Class frmShowDocumentatie
'local variables to get passed the public shared values from
'curent selected row index and document name in datagridview
Private iRow As Integer
Private fName As String
Private Sub frmShowDocumentatie_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'sets the mdi parent
MdiParent = MDIParent1
'sets the text of the form to the filename of pdf bestand
Me.Text = "Document: " & getFilename()
'loads the pdf bestand, need the filepath which is provided by getfilepath function
AxAcroPDF1.src = GetFilePath()
'gets the values from the selected row index and corrsponding filename
iRow = frmDataView.rowIndex
fName = frmDataView.FileName
tsmiDocument.Text = "Document: " & getFilename()
End Sub
'function for getting the filename of selected pdf file in datagridview
Public Function getFilename() As String
fName = frmDataView.FileName
getFilename = fName
End Function
'gets the file path of selected pdf bestand
Function GetFilePath() As String
'Dim i As Integer = frmVerledenOverzicht.dgvData.CurrentRow.Index
'Dim filename As String = frmVerledenOverzicht.dgvData.Item(6, i).Value
Dim sFilePath As String
Dim buffer As Byte()
Using conn As New SqlConnection("Server=.\SQLEXPRESS;Initial Catalog=AndriesKamminga;Integrated Security=True;Pooling=False")
conn.Open()
Using cmd As New SqlCommand("Select Bestand From dbo.PaVerledenOverzicht WHERE Documentatie =" & "'" & getFilename() & "';", conn)
buffer = cmd.ExecuteScalar()
End Using
conn.Close()
End Using
sFilePath = System.IO.Path.GetTempFileName()
System.IO.File.Move(sFilePath, System.IO.Path.ChangeExtension(sFilePath, ".pdf"))
sFilePath = System.IO.Path.ChangeExtension(sFilePath, ".pdf")
System.IO.File.WriteAllBytes(sFilePath, buffer)
'returns the file path needed for AxAcroPDF1
GetFilePath = sFilePath
End Function
Private Sub tsmiSluiten_Click(sender As Object, e As EventArgs) Handles tsmiSluiten.Click
Try
Me.Close()
Catch ex As Exception
MessageBox.Show(ex.Message, "Database Info", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
End Class
anyone knows what's causing this exception and why is the program crashing instead of being caught in the try catch block
Am using visual studio community edition 2017

Get the folder name from a path

There is a directory whose name is temp. It contains various folders of different names. I want to delete the folder of specific name such as test. How to delete that in vb.net. Please help me.
Be careful with following code and edit the code for your needs:
Imports System.IO
Public Class Form1
Private Sub btnDelete_Click(sender As Object, e As EventArgs) Handles btnDelete.Click
Dim directoryName As String = "D:\_working"
Dim subPath = directoryName & "\TEST" '// be careful - subPath will be deleted!
Try
Dim directoryExists = Directory.Exists("D:\_working")
Dim subDirectoryExists = Directory.Exists(subPath)
MessageBox.Show("top-level directory exists: " & directoryExists)
MessageBox.Show("sub-directory exists: " & subDirectoryExists)
For Each deleteFile In Directory.GetFiles(subPath, "*.BMP", SearchOption.TopDirectoryOnly)
File.Delete(deleteFile)
'// you may want to log all deleted files here ...
Next
Directory.Delete(subPath) '// without the need of logging add ..(subPath, true)
Catch ex As Exception
MessageBox.Show("The process failed: {0}", ex.Message)
End Try
End Sub
End Class
Make sure you Imports System.IO
then you can just do this
File.Delete(path)
where path is a string equal to the value of your path.

How to save a textbox value into a folder as .txt and get the time stamp as filename using VB?

Here is my code:
Private CurrentRecipient As String
Private User As String = "Name"
Dim UserFolder As String
Dim FileName As String = Format(Now, "MMMMDDDDYYYYHHNNSS") & ".txt"
Private Sub SendButton_Click(sender As Object, e As EventArgs) Handles
SendButton.Click
If CurrentRecipient = "Edward" Then
UserFolder = "C:\Users\bele\Desktop\Edward'sFolder" & FileName
ElseIf CurrentRecipient = "Criziel" Then
UserFolder = "C:\Users\bele\Desktop\Criziel'sFolder" & FileName
End If
' I received no error but once I have send a message It does not doe anything :(
Try this. Add the following Imports above your Form Class.
Imports System
Imports System.IO
Imports System.Text
You will need to add a TextBox control named txtFolderName to enter the folder names (Edward's or Criziel)for this to work. Enter the name of the folder on the Desktop (Edward's or Criziel) into txtFolderName, Click the button named Button1 and it will create the file inside the correct folder.
I'm guessing this is just testing code ideas, because you should also make the Directory Path a variable that you can enter in a TextBox
Private Sub SaveFile()
Dim UserFolder As String = ""
Dim FileName As String = DateTime.Now.ToString("MMddyyyyHHmmss") & ".txt"
Dim fs As FileStream
UserFolder = "C:\Users\bele\Desktop\" & txtFolderName.Text & "\" & FileName
' Create a file
fs = File.Create(UserFolder)
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
SaveFile()
End Sub
Good Luck!
Comment out the fs = File.Create(UserFolder) line and add this code just below it.
Using sw As StreamWriter = File.CreateText(UserFolder)
sw.WriteLine("Hello")
sw.WriteLine("And")
sw.WriteLine("Welcome")
End Using

upload multiple files to a local folder in vb.net

I am trying to create a function that will allow user to upload multiple files to a local folder.
currently i am able to upload just one file. i needed to upload more files in one go.
what i use for opening files/folder
a.Multiselect = True
If a.ShowDialog() = Windows.Forms.DialogResult.OK Then
removeatt.Show()
removeatt.Text = "Remove Attachment"
fpath.Text = a.FileName
address.Text = System.IO.Path.GetFileName(a.FileName)
Dim file As String
file = fpath.Text.ToString
Label7.Text = file
If fpath.Text = "-" Then
removeatt.Hide()
Else
removeatt.Show()
End If
End If
what i use for saving attachment
If fpath.Text = "-" Then
Else
My.Computer.FileSystem.CopyFile(fpath.Text = "-", dir2 + Upload.Label16.Text, Microsoft.VisualBasic.FileIO.UIOption.AllDialogs, Microsoft.VisualBasic.FileIO.UICancelOption.DoNothing)
End If
any help is appreciated
thanks
It is not entirely clear to me where you handle the selected files, the first one is about removing attachments and the saving-part is not about uploading, it saves a file to the disk of the user as it seems.
Generally i'd recommend you to write a function that handles one file at a time so you can feed the function with the list of files to be copied in a for each-loop. The function is a bit "basic" to demonstrate what i mean.
Public Function CopyToDisk(ByVal DestinationPath As String, ByVal Sourcepath As String) As String
If Not System.IO.File.Exists(Sourcepath) Then
Return "Source missing" & Sourcepath
End If
Try
File.Copy(Sourcepath, DestinationPath)
Catch ex As Exception
Return ex.Message
End Try
Return "ok"
End Function
Well, have a look at the example from MSDN here, it has a filepicker and then it puts the objects in an array you can loop through and copy it where you want it to copy.
Here is the MSDN-original
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
InitializeOpenFileDialog()
End Sub
Private Sub Selectfilebutton_Click_1(sender As Object, e As EventArgs) Handles Selectfilebutton.Click
Dim dr As DialogResult = Me.OpenFileDialog1.ShowDialog()
If (dr = System.Windows.Forms.DialogResult.OK) Then
' Read the files
Dim file As String
For Each file In OpenFileDialog1.FileNames
'' you can loop through the array of objects and use a function to do the copying
' so for instance with my function it would be :
' copytodisk(Destination, file.filename)
' Create a PictureBox for each file, and add that file to the FlowLayoutPanel.
Try
Dim pb As New PictureBox()
Dim loadedImage As Image = Image.FromFile(file)
pb.Height = loadedImage.Height
pb.Width = loadedImage.Width
pb.Image = loadedImage
FlowLayoutPanel1.Controls.Add(pb)
Catch SecEx As SecurityException
' The user lacks appropriate permissions to read files, discover paths, etc.
MessageBox.Show("Security error. Please contact your administrator for details.\n\n" & _
"Error message: " & SecEx.Message & "\n\n" & _
"Details (send to Support):\n\n" & SecEx.StackTrace)
Catch ex As Exception
' Could not load the image - probably permissions-related.
MessageBox.Show(("Cannot display the image: " & file.Substring(file.LastIndexOf("\"c)) & _
". You may not have permission to read the file, or " + "it may be corrupt." _
& ControlChars.Lf & ControlChars.Lf & "Reported error: " & ex.Message))
End Try
Next file
End If
End Sub
Public Sub InitializeOpenFileDialog()
' Set the file dialog to filter for graphics files.
Me.OpenFileDialog1.Filter = _
"Images (*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF|" + _
"All files (*.*)|*.*"
' Allow the user to select multiple images.
Me.OpenFileDialog1.Multiselect = True
Me.OpenFileDialog1.Title = "My Image Browser"
End Sub

vb.net how to start a folder monitor service at runtime and pass on the folder path to monitor?

I have the following windows service file:
Imports System.ServiceProcess
Imports System.IO
Public Class fswService
Dim fsw As FileSystemWatcher
Dim lf As StreamWriter
Protected Overrides Sub OnStart(ByVal args As String())
' Add code here to start your service. This method should set things
' in motion so your service can do its work.
lf = New StreamWriter(Application.StartupPath & "\fsw_lg.log")
fsw = New FileSystemWatcher()
fsw.Path = args(0)
fsw.IncludeSubdirectories = True
fsw.Filter = ".txt"
fsw.EnableRaisingEvents = True
AddHandler fsw.Created, New FileSystemEventHandler(AddressOf file_created)
AddHandler fsw.Changed, New FileSystemEventHandler(AddressOf file_changed)
AddHandler fsw.Deleted, New FileSystemEventHandler(AddressOf file_deleted)
End Sub
Public Sub file_created(ByVal obj As Object, ByVal e As FileSystemEventArgs)
lf.WriteLine(Now.ToShortDateString & "-" & Now.ToShortTimeString & "-" & e.FullPath & "-created")
End Sub
Public Sub file_changed(ByVal obj As Object, ByVal e As FileSystemEventArgs)
lf.WriteLine(Now.ToShortDateString & "-" & Now.ToShortTimeString & "-" & e.FullPath & "-changed")
End Sub
Public Sub file_deleted(ByVal obj As Object, ByVal e As FileSystemEventArgs)
lf.WriteLine(Now.ToShortDateString & "-" & Now.ToShortTimeString & "-" & e.FullPath & "-deleted")
End Sub
Protected Overrides Sub OnStop()
lf.Close()
End Sub
End Class
i have the ServiceName set to fswService (same as class name). When I added an installer I also set the ServiceName for the ServiceInstaller1 as fswService.
I want to start this service at runtime based on the user setting the path of the folder to be watched. To achieve this I have the following:
Dim fsw_controller As New ServiceProcess.ServiceController
fsw_controller.Start(fswService)
2 problems: first, intellisense error saying: 'fswService' is a type and cannot be used as an expression. second, I can not figure out a way to pass on to the service the path of the folder to watch (which is stored at My.Settings.userPath).
I really thought this is how you start a service. Am I missing something?
Your help is, as always, appreciated.
Thanks
ok. I think I figured them both out but I am getting an error when I run the application.
In the service file I changed
fsw.Path = args(0)
To
fsw.Path = My.Settings.userPath
To fix starting the service (as I mentioned in my comment) I did:
Dim fsw_controller As New ServiceController("fswService")
fsw_controller.Start()
i rebuilt the application, re-installed the service using installutil.exe and ran it. But I am getting an error:
InvalidOperationException was unhandled
Cannot start service fswService on computer '.'.
Any help with that?? Please..
You can only send an integer value (between 128-255) through the ServiceController.ExecuteCommand procedure. You then override the OnCustomCommand event in your Windows Service, which runs when the ExecuteCommand is sent to that specific service. I would save the name of the folder to be watched in a text file and just have the OnCustomCommand event look into that file for the folder. You are probably getting that error because you ran the Start procedure of the ServiceController when the Windows Service was already running. To update the ServiceController.Status property, run the StatusController.Refresh() procedure.