How would I open a program within Visual Basic 2010? - vb.net

How would I open a program within Visual Basic 2010? (Like running "Application.txt" from "C:\" within a Visual Basic project.
Public Class getfrom
Dim getfrom As String
Dim saveto As String
Dim download As Boolean
Function openRunt()
Dim myProcess As New Process()
Try
myProcess.StartInfo.UseShellExecute = False
myProcess.StartInfo.FileName = "C:\\Runt.exe"
myProcess.StartInfo.CreateNoWindow = True
myProcess.Start()
Catch e As Exception
' do nothing.
End Try
Return False
End Function
Function setVariables()
' Download the file from..
getfrom = "http://sourceforge.net/projects/iforsm/files/iForsm.exe"
' Download the file to..
saveto = "C:\Runt.exe"
' Allow download..
download = True
Return False
End Function
Private Sub getfrom_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
setVariables()
If download = True Then
My.Computer.Network.DownloadFile(getfrom, saveto)
Dim fileExists As Boolean
fileExists = My.Computer.FileSystem.FileExists("C:\Runt.exe")
If fileExists = True Then
'System.Diagnostics.Process.Start("notepad.exe", "c:\Application.txt")
openRunt()
End If
Else
End
End If
'End
End Sub
End Class

If you mean opening the text file with the notepad program via your application then something like the following should do the trick.
System.Diagnostics.Process.Start("notepad.exe", "c:\Application.txt")
See: http://msdn.microsoft.com/en-us/library/system.diagnostics.process.start.aspx

You would use the ProcessStart mechanism, see the link below for a tutorial.
This is located within the System.Diagnostics namespace.
Thanks
Pete
Process Start Tutorial

Related

Moving files into new folder using VB

I have one Log file that keep a full path for *.docx extension every time it's created. The problem is I don't know how to split the file's name from the full path. Before move it, I can select which Path that have been created using CheckedListBox and move it to target folder.
For example in my Log File I store (file has been created: C:\Users\AsrahLim\Desktop\New Microsoft Word Document.docx), all I need is the file's name "New Microsoft Word Document.docx" and move it to new folder .
This is my target folder: C:\Users\AsrahLim\Google Drive. Below is my code.
Imports System.IO
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
CheckedListBox1.Items.Add("Select/UnSelect All")
CheckedListBox1.CheckOnClick = True
Dim FILE_NAME As String = "C:\Users\AsrahLim\Desktop\LogFile.txt"
If System.IO.File.Exists(FILE_NAME) Then
Dim objReader As New System.IO.StreamReader(FILE_NAME)
Do While objReader.Peek() <> -1
CheckedListBox1.Items.Add(objReader.ReadLine())
btnSave.Enabled = True
Loop
Else
MessageBox.Show("File Does Not Exist")
Close()
End If
End Sub
Private Sub btnSave_Click(sender As System.Object, e As System.EventArgs) Handles btnSave.Click
If CheckedListBox1.CheckedItems.Count <> 0 Then
For i As Integer = 0 To CheckedListBox1.CheckedItems.Count - 1
Dim SourcePath As String = CheckedListBox1.SelectedItem
Dim MoveLocation As String = "C:\Users\AsrahLim\Google Drive"
SourcePath = SourcePath.Substring(SourcePath.LastIndexOf("- ") + 1)
If File.Exists(SourcePath) = True Then
File.Move(SourcePath, MoveLocation)
MsgBox("File Moved")
Else
MsgBox("File Not move")
End If
Next
End If
End Sub
Private Sub btnCancel_Click(sender As System.Object, e As System.EventArgs) Handles btnCancel.Click
Close()
End Sub
End Class
Don't try to implement your own logic for path manipulations. Use the shared Path class in System.IO instead.
Dim filename As String = Path.GetFileName(SourcePath)
Then you can construct the new path name with
Dim destinationPath As String = Path.Combine(MoveLocation, filename)
Also, test if the file exists in the destination location as well and delete it if it exists.
If File.Exists(SourcePath) Then
Dim filename As String = Path.GetFileName(SourcePath)
Dim destinationPath As String = Path.Combine(MoveLocation, filename)
If File.Exists(destinationPath) Then
File.Delete(destinationPath)
End If
File.Move(SourcePath, destinationPath)
MsgBox("File Moved")
Else
MsgBox("File Not move")
End If
A side note: I don't like statements like If File.Exists(SourcePath) = True Then. Often people think that an If-statement requires a comparison. This is not true. All it needs is a Boolean expression, i.e. an expression returning either True or False. File.Exists(SourcePath) is an expression which does exactly this. The additional = True doesn't change anything and is superfluous, because if File.Exists(SourcePath) returns True then True = True is True and if File.Exists(SourcePath) returns False then False = True is False. = True is a neutral operation as is * 1 for numbers. You don't say Foo(1 * x), you just say Foo(x).
Very simple in your log you could store with a delimiter for instance:
New File Created*C:\test.docx
The star symbol is a banned character in file name so you can be sure it wont be in the path. After this you can just do
Dim data() As String
data = Split(File.ReadAllText(LogFile.txt), StringSplitOptions.RemoveEmptyEntries)
File.Move(data(1), Path.Combine(MoveLocation , Path.GetFileName(data(1)))
Ideally you just shouldn't store files a bit everywhere on your computer and use distinct folders.

User input on command prompt

I need to automate usage of a command line utility in VB.net. here is an example.
From the code, I need to decrypt a file using command line utility. Here is the command line procedure.
You start utility using this line
C:\gnupg>gpg --decrypt c:\temp\File_Encr.xml
Once executed, then it shows this
You need a passphrase to unlock the secret key for
user: "xxxx <abc#def.com>"
1024-bit ELG-E key, ID ABCD, created 2013-10-25 (main key ID DEF)
Enter passphrase:
and when you enter the passphrase, it do the job.
I need start this process from the code (VB.NET) and input passphrase as well so that it doesn't require any user interaction. My code will be used in Windows Services as well as Web application.
Can someone help on this please?
Thank you.
Sameers
Here is a code snippet I use.
All output code is written to the Visual Studio debug window for convenience. All program output all redirected to output handlers. This allows you to inspect the output coming out of the program in "real time". If you needed to watch the output lines and scan for a certain phrase and then perform an action, you could easily do this in Sub OutputReceivedHandler().
I tried to make it generic so you can see how it works:
Imports Microsoft.VisualBasic
Imports System.Diagnostics
Imports System
Public Class ExternalUtilities
Private myprocess As Process
Private SW As System.IO.StreamWriter
Private myprocess_HasError As Boolean = False
Private myprocess_ErrorMsg As String = ""
Private myprocess_Output As String = ""
Public Sub New()
' do init stuff here.
' maybe pass the executable path, or command line args.
End Sub
Public Sub launchUtilityProcess1()
Dim executeableFullPath As String = "C:\Path\To\file.exe"
' define the process
myprocess = New Process
myprocess.StartInfo.FileName = executeableFullPath
myprocess.StartInfo.RedirectStandardInput = True
myprocess.StartInfo.RedirectStandardOutput = True
myprocess.StartInfo.RedirectStandardError = True
myprocess.StartInfo.UseShellExecute = False
myprocess.StartInfo.CreateNoWindow = True
myprocess.StartInfo.WorkingDirectory = System.IO.Path.GetDirectoryName(executeableFullPath)
myprocess.StartInfo.Arguments = "--decrypt c:\temp\File_Encr.xml"
' add handlers to monitor various conditions
myprocess.EnableRaisingEvents = True
AddHandler myprocess.OutputDataReceived, AddressOf OutputReceivedHandler
AddHandler myprocess.ErrorDataReceived, AddressOf ErrorReceivedHandler
AddHandler myprocess.Exited, AddressOf ExitedHandler
' launch
Try
myprocess.Start()
' redirect this processes IO
SW = myprocess.StandardInput
SW.AutoFlush = True
' use asynchronous reading so buffers dont fill up
myprocess.BeginOutputReadLine()
myprocess.BeginErrorReadLine()
' wait for program to end
myprocess.WaitForExit()
myprocess.Close()
SW.Close()
myprocess.Dispose()
' check for errors
If myprocess_ErrorMsg "" Then
' something bad happened, handle it.
End If
Catch ex As Exception
' something bad happened, handle it.
End Try
End Sub
Private Sub OutputReceivedHandler(ByVal sendingProcess As Object, ByVal line As DataReceivedEventArgs)
If Not line.Data Is Nothing Then
If line.Data = "string to search for..." Then
' when this string is detected, send more output
SW.Write("helloworld" & System.Environment.NewLine)
ElseIf line.Data = "something else..." Then
' when this string is detected, send more output
SW.Write("goodbyeworld" & System.Environment.NewLine)
End If
Debug.WriteLine(line.Data)
End If
End Sub
Private Sub ErrorReceivedHandler(ByVal sendingProcess As Object, ByVal line As DataReceivedEventArgs)
Debug.WriteLine(line.Data)
' These executables send newlines on the STDERR path, ignore newlines
If line.Data <> "" Then
myprocess_HasError = True
myprocess_ErrorMsg = line.Data
End If
End Sub
Private Sub ExitedHandler(ByVal sender As Object, ByVal e As System.EventArgs)
Debug.WriteLine("Process Exited")
End Sub
End Class

closing msaccess.exe in vb.net

I am working on creating a vb.net program i have a button that when clicked on will browse for MDB files (code 1) and when selected will execute some lines of code that will populate all of the macros within the access database into a combo box (code 2). The problem i'm having is MSACCESS.EXE process is not closing after code 2 runs. I've tried a couple different things like objAccess.CloseCurrentDatabase() none of which are working.. Any ideas on what i'm doing wrong?
code 1
Private Sub CommandDBPath_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CommandDBPath.Click
Dim dialog As New OpenFileDialog()
dialog.Filter = "Access database (*.mdb)|*.mdb"
If DialogResult.OK = dialog.ShowDialog Then
TextDBPath.Text = dialog.FileName
End If
SelectDatabaseMacro()
End Sub
code 2
Private Sub SelectDatabaseMacro()
Dim objAccess As Object '' Access.Application
Dim i As Long
Dim path As String
path = TextDBPath.Text
objAccess = CreateObject("Access.Application")
objAccess.OpenCurrentDatabase(path)
For i = 0 To objAccess.CurrentProject.AllMacros.Count - 1
TextReportMacro.Items.Add(objAccess.CurrentProject.AllMacros(i).Name)
Next
objAccess.CloseCurrentDatabase()
objAccess = Nothing
End Sub
Try adding an objAccess.Quit statement after you objAccess.CloseCurrentDatabase().
To abruptly kill the process,
For Each p As Process In Process.GetProcesses()
If p.ProcessName = "MSAccess" Then
p.Kill()
End If
Next
Or for a more "graceful" approach, try this,
The process must have a windows interface (window) in order to work.
For Each p As Process In Process.GetProcesses()
If p.ProcessName = "MSAccess" Then
p.CloseMainWindow()
End If
Next

Move file in Windows-Service

This is my first time making a windows service app. I'm trying to move files from one folder to another using a windows service app. It'll do so every 10 seconds.
This is the code I'm using. It works when I use it on a windows form app but doesn't work when I use it on a windows-service app.
The code in the Timer1_Tick works if I use it in OnStart. But doesn't work in the timer.
Protected Overrides Sub OnStart(ByVal args() As String)
Timer1.Enabled = True
End Sub
Protected Overrides Sub OnStop()
Timer1.Enabled = False
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Dim FileToMove As String
Dim MoveLocation As String
Dim count1 As Integer = 0
Dim files() As String = Directory.GetFiles("C:\Documents and Settings\dmmc.operation\Desktop\Q8")
Dim pdfFiles(100) As String
For i = 0 To files.Length - 1
If Path.GetExtension(files(i)) = ".pdf" Then
pdfFiles(count1) = files(i)
count1 += 1
End If
Next
For i = 0 To pdfFiles.Length - 1
If pdfFiles(i) <> "" Then
FileToMove = pdfFiles(i)
MoveLocation = "C:\Documents and Settings\dmmc.operation\Desktop\Output\" + Path.GetFileName(pdfFiles(i))
If File.Exists(FileToMove) = True Then
File.Move(FileToMove, MoveLocation)
End If
End If
Next
End Sub
Windows.Forms.Timer won't work without a Form instantiated. You should be using System.Timers.Timer instead:
Private WithEvents m_timer As System.Timers.Timer
Protected Overrides Sub OnStart(ByVal args() As String)
m_timer = New System.Timers.Timer(1000) ' 1 second
m_timer.Enabled = True
End Sub
Private Sub m_timer_Elapsed(ByVal sender As Object, ByVal e As System.Timers.ElapsedEventArgs) Handles m_timer.Elapsed
m_timer.Enabled = False
'Do your stuff here
m_timer.Enabled = True
End Sub
I've also build a service that moves files that are dropped into a folder but I'm using the FileSystemWatcher. The FileSystemWatcher allows me to move the file when a new one is created, create an entry in a SQL Database and send an email notification when it's all done.
This is how I have setup the FileSystemWatcher
Set a folder to watch: watcher.Path = "C:\Folder to Watch"
Set the file type to watch: watcher.Filter = "*.pdf".
The type of event to watch and the Method that gets triggered: watcher.Created += new FileSystemEventHandler(OnChanged);
Lastly, I need to enable the event: watcher.EnableRaisingEvents = true;
Unfortunately, I have instances on a daily basis where the files do not get moved successfully. I get IO exceptions for file in use. The files get copied but the file in the destination folder is 0kb.
I'm trying to troubleshoot it and I've manage to debug remotely but I still haven't figured out what I am doing wrong.
The most common error I get is: Error: System.IO.IOException: The process cannot access the file 'fileName.pdf' because it is being used by another process.
this error does not make sense as the file did not exist prior to my service trying to move it...
Any further help would be appreciated.

OpenFileDialog under the hood

This is my first question here because I ended up in dead end.
I'm using ZIP 2 Secure EXE (very good software from Chilkat) to create setup.exe for application. ZIP 2 Secure EXE can be run without GUI with one or more parameters.
The problem is that when I call ZIP 2 Secure EXE (ChilkatZipSE.exe) without using OpenFileDialog form to determine location of ChilkatZipSE.exe, it doesn't run process with System.Diagnostics.Process class. The way I call ChilkatZipSE.exe is "..\ChilkatZipSE.exe -cfg settings.xml". Everything is OK with settings.xml and there is UnlockCode node which is needed for creating setup.exe file. When I use OpenFileDialog ChilkatZipSE.exe creates desired setup.exe and it's working fine.
Bellow is my code that I use:
Private Sub btnStartApp_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStartApp.Click
If txtExtAppPath.Text.Length > 0 AndAlso System.IO.File.Exists(txtExtAppPath.Text) Then
Dim myFile As New FileInfo(txtExtAppPath.Text)
txtExtAppLog.Text = StartApplication(myFile.FullName, txtExtParams.Text, chkIsHidden.Checked)
'txtExtAppLog.Text = StartApplication(txtExtAppPath.Text, txtExtParams.Text, chkIsHidden.Checked)
End If
End Sub
Public Function StartApplication(ByVal fileFullPath_ As String, ByVal fileParameter_ As String, ByVal isHidden_ As Boolean) As String
Dim lassie As String = String.Empty
Try
Dim newProcess As New ProcessStartInfo()
newProcess.FileName = fileFullPath_
newProcess.Arguments = fileParameter_
If isHidden_ Then newProcess.WindowStyle = ProcessWindowStyle.Hidden
If System.IO.File.Exists(fileFullPath_) Then
Using startedNewProcess As Process = Process.Start(newProcess)
'startedNewProcess.EnableRaisingEvents = True
startedNewProcess.WaitForExit()
End Using
Else
lassie = "File " + fileFullPath_ + " doesn't exist."
End If
Catch ex As Exception
lassie = ex.Message
End Try
Return lassie
End Function
Thanks, magnumx.
the problem was the given parameter. When using OpenFileDialog it knows where settings.xml is. But when calling "..\ChilkatZipSE.exe -cfg settings.xml" without OpenFileDialog it must be used as "..\ChilkatZipSE.exe -cfg ..\settings.xml"