Running script in selected path - vb.net

I currently have this piece of code:
Sub Button1Click(sender As Object, e As EventArgs)
If dlgFolder.ShowDialog = Windows.Forms.DialogResult.OK Then
txtPath.Text = dlgFolder.SelectedPath
Try
Dim CopyFile As String = Path.Combine(Directory.GetCurrentDirectory, "pdftk.exe")
Dim CopyLocation As String = Path.Combine(dlgFolder.SelectedPath, "pdftk.exe")
Dim pyScript As String = Path.Combine(Directory.GetCurrentDirectory, "pdfmerge.py")
Dim pyLocation As String = Path.Combine(dlgFolder.SelectedPath, "pdfmerge.py")
System.IO.File.Copy(CopyFile, CopyLocation, True)
System.IO.File.Copy(pyScript, pyLocation, True)
Catch copyError As IOException
Console.WriteLine(copyError.Message)
End Try
End If
End Sub
This copies two files in the current working directory (which will be the default install folder) to the selected path from the Fodler Dialog Browser. This works correctly.
Now what I want to do is too run "pdfmerge.py" into the selected folder path. I tried the below code but the script is still running in the current working directory.
Sub BtnNowClick(sender As Object, e As EventArgs)
Dim myProcess As Process
Dim processFile As String = Path.Combine(dlgFolder.SelectedPath, "pdfmerge.py")
myProcess.Start(processFile, dlgFolder.SelectedPath)
End Sub

You can set the process's working directory.
Dim p As New ProcessStartInfo
p.FileName = Path.Combine(dlgFolder.SelectedPath, "pdfmerge.py")
p.WorkingDirectory = dlgFolder.SelectedPath
Process.Start(p)
One question: are you ensuring the dlgFolder.SelectedPath is correct? Without knowing the inner workings of your program, it appears possible to press BtnNow before Button1, meaning dlgFolder.SelectedPath won't have been set by the user.

Try using the overload of Process.Start() that takes 5 arguments.
Start ( _
fileName As String, _
arguments As String, _
userName As String, _
password As SecureString, _
domain As String _
)
You may be able to pass in null for userName and password, but if your directory is outside of the standard ones that you have permission for, you may need to put your username and password in. domain would be the working directory, I think.

Related

Moving Files From One Folder To Another VB.Net

I am trying to figure out how to move 5 files
settings.txt
settings2.txt
settings3.txt
settings4.txt
settings5.txt
from one folder to another.
Although I know what the file names will be and what folder Name they will be in, I don't know where that folder will be on the Users computer.
My thought process is to use a FolderBrowseDialog which the user can browse to where the Folder is, and then when OK is pressed, it will perform the File copy to the destination folder, overwriting what's there.
This is what I have so far.
Dim FolderPath As String
Dim result As Windows.Forms.DialogResult = FolderBrowserImport.ShowDialog()
If result = DialogResult.OK Then
FolderPath = FolderBrowserImport.SelectedPath & "\"
My.Computer.FileSystem.CopyFile(
FolderPath & "settings.txt", "c:\test\settings.txt", overwrite:=True)
ElseIf result = DialogResult.Cancel Then
Exit Sub
End If
Rather than run this 5 times, is there a way where it can copy all 5 files at once
I know why IdleMind recommended the approach they did, but it would probably make for a bit more readable code to just list out the file names:
Imports System.IO
...
Dim result = FolderBrowserImport.ShowDialog()
If result <> DialogResult.OK Then Exit Sub
For Each s as String in {"settings.txt", "settings2.txt", "settings3.txt", "settings4.txt", "settings5.txt" }
File.Copy( _
Path.Combine(FolderBrowserImport.SelectedPath, s), _
Path.Combine("c:\test", s), _
True _
)
Next s
You can swap this fixed array out for a list that VB prepares for you:
For Each s as String in Directory.GetFiles(FolderBrowserImport.SelectedPath, "settings*.txt", SearchOption.TopDirectoryOnly)
File.Copy(s, Path.Combine("c:\test", Path.GetFilename(s)), True)
Next s
Tips:
It's usually cleaner to do a If bad Then Exit Sub than a If good Then (big load of indented code) End If - test all your known failure conditions at the start and exit the sub if anything fails, rather than arranging a huge amount of indented code
Use Path.Combine to combine path and filenames etc; it knows how to deal with stray \ characters
Use Imports to import namespaces rather than spelling everything out all the time (System.Windows.Forms.DialogResult - a winforms app will probably have all the necessaries imported already in the partial class so you can just say DialogResult. If you get a red wiggly line, point to the adjacent lightbulb and choose to import System.WIndows/Forms etc)
Once you have the selected folder, use a For loop to build up the names of the files you're looking for. Use System.IO.File.Exists() to see if they are there. Use System.IO.Path.Combine() to properly combine your folders with the filenames.
Here's a full example (without exception handling, which should be added):
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If FolderBrowserImport.ShowDialog() = DialogResult.OK Then
Dim FolderPath As String = FolderBrowserImport.SelectedPath
For i As Integer = 1 To 5
Dim FileName As String = "settings" & If(i = 1, "", i) & ".txt"
Dim FullPathFileName As String = System.IO.Path.Combine(FolderPath, FileName)
If System.IO.File.Exists(FullPathFileName) Then
Dim DestinationFullPathFileName = System.IO.Path.Combine("c:\test", FileName)
My.Computer.FileSystem.CopyFile(FullPathFileName, DestinationFullPathFileName, True)
Else
' possibly do something in here if the file does not exist?
MessageBox.Show("File not found: " & FullPathFileName)
End If
Next
End If
End Sub

VB.NET stopping strings being automatically split by spaces

I am building a program in VB that populates a listbox with all the songs in a chosen folder and opens them with media player when you click on them in the list. All of that works but my problem is that pretty much no matter what I do (I've tested this with WMP, VLC, and Winamp) it splits up the argument string by spaces, for example if the file path is C:\Program Files (x86)\Test song.mp3, it will try to open in sequence: C:\Program, then Files, then (x86)\Test, then song.mp3. It works on file paths containing no spaces, but else it always fails.
Private Sub SongListBox_Click(sender As Object, e As EventArgs) Handles SongListBox.Click
Dim song As String = SongListBox.SelectedIndex
If SongListBox.SelectedIndex = "-1" Then
Else
Dim SongPath As String = Pathlist.Items.Item(song)
Dim SongProcess As New ProcessStartInfo
SongProcess.FileName = "C:\Program Files\Winamp\winamp.exe"
SongProcess.Arguments = SongPath
SongProcess.UseShellExecute = True
SongProcess.WindowStyle = ProcessWindowStyle.Normal
MsgBox(Pathlist.Items.Item(song), MsgBoxStyle.Information, "Song")
Dim SongStart As Process = Process.Start(SongProcess)
SongListBox.Select()
End If
End Sub

Open, Launch or Show a file for the user to read or write in vb.net

It sounds very simple but I have searched and cannot seem to find a way to open a log file which the user just created from my windows form app. The file exits I just want to open it after it is created.
I have a Dim path As String = TextBox1.Text and once the user names and clicks ok on the savefiledialog I have a msgbox that says "Done" and when you hit OK I have tried this
FileOpen(FreeFile, path, OpenMode.Input) but nothing happens. I just want it to open the log and show it to the user so they can edit or save it again or anything.
This is where I got the above code.
http://msdn.microsoft.com/en-us/library/microsoft.visualbasic.filesystem.fileopen.aspx
Searching is difficult because everyone is trying to "Open" a file and process it during runtime. I am just trying to Show a file by Launching it like someone just double clicked it.
Here is the entire Export Button click Sub. It basically writes listbox items to file.
Private Sub btnExport_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExport.Click
Dim sfd As New SaveFileDialog
Dim path As String = TextBox1.Text
Dim arypath() As String = Split(TextBox1.Text, "\")
Dim pathDate As String
Dim foldername As String
foldername = arypath(arypath.Length - 1)
pathDate = Now.ToString("yyyy-MM-dd") & "_" & Now.ToString("hh;mm")
sfd.FileName = "FileScannerResults " & Chr(39) & foldername & Chr(39) & " " & pathDate
sfd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal)
sfd.Filter = "Text files (*.txt)|*.txt|CSV Files (*.csv)|*.csv"
sfd.ShowDialog()
path = sfd.FileName
Using SW As New IO.StreamWriter(path)
If CkbxFolder.Checked = True Then
SW.WriteLine("Folders")
For Each itm As String In ListBox1.Items
SW.WriteLine(itm)
Next
End If
If CkbxFiles.Checked = True Then
SW.WriteLine("Files")
For Each itm As String In ListBox2.Items
SW.WriteLine(itm)
Next
End If
End Using
MsgBox("Done...")
FileOpen(FreeFile, path, OpenMode.Input) 'Why can't I open a file for you...
End Sub
Do not use the old VB6 methods. They are still here for compatibility reason, the new code should use the more powerful methods in the System.IO namespace.
However, as said in comments, FileOpen don't show anything for you, just opens the file
You coud write
Using sr = new StreamReader(path)
Dim line = sr.ReadLine()
if !string.IsNullOrEmpty(line) Then
textBoxForLog.AppendText(line)
End If
End Using
or simply (if the file is not too big)
Dim myLogText = File.ReadAllText(path)
textBoxForLog.Text = myLogText
As alternative, you could ask the operating system to run the program associated with the file extension and show the file for you
Process.Start(path)
To get the same behavior as if the user double-clicked it, just use System.Diagnostics.Process, and pass the filename to it's Start method:
Process.Start(path)
This will open the file using whatever the default application is for that filename based on its extension, just like Explorer does when you double-click it.

code that doesn't work...Kill-process , search-for-file , streamwrite on file searched file

can you help me with that code ?
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim x As String = "C:\Users\Andy\Documents\Visual Studio 2008\Projects\minecraft srv\"
For Each app As Process In Process.GetProcesses
If app.ProcessName = "notepad" Then
app.Kill()
End If
Next
Dim result As String
Dim servprop() As String
servprop = System.IO.Directory.GetFiles(x, "server.*")
For Each file In servprop
result = Path.GetFileName(file)
Next
Dim z As String = "C:\Users\Andy\Documents\Visual Studio 2008\Projects\minecraft srv\" & result.ToString
Dim t As StreamWriter = New StreamWriter(z)
t.WriteLine(TextBox1.Text.ToString)
t.Close()
End Sub
so... I got a button (button1) that finds if notepad is opened and kills it.
Then it searches for "server.Properties" in "x" location
if server.properties is found , then "result" will get his name (server)
"z" is the file location where streamwriter must write the text from textbox1 .
And it doesn't work... streamwirter is not writing on server.properties ... why ?
mention : I'm just a kid :D and i'm trying to learn by myself visual basic .
If you have only one file called "server.properties" then you could remove all the code that search for this file and write it directly.
Dim z As String
z = System.IO.Path.Combine(x, "server.properties")
Using t = New StreamWriter(z)
t.WriteLine(TextBox1.Text.ToString)
t.Flush()
End Using
Regarding the error, encapsulating the writing code with a proper using statement ensures a complete clean-up. Also adding a call to Flush() is probably not necessary, but doesn't hurt.

File Icons and List view

How to retrieve file icons associated with the file types and add them with the items of Listview in vb.net
I read about SHGetFileInfo but I didn't understand anything from that
please give me solution or please explain me ho system works with the .net controls in details
Having looked up SHGetFileInfo I can see why you're confused by it, but I think it might be slightly overkill for what I think you're trying to do i.e. enumerating the contents of a folder and adding items to the Listview.
If we have a form that contains a ListView and an ImageList, with the two related by having the ListView's LargeImageList property set to the ImageList, then here's how we put the contents of a folder into the ListView with the icons coming from the associated EXE file for each file.
Imports System.IO
Imports System.Drawing
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim dirInfo As DirectoryInfo
Dim fileInfo As FileInfo
Dim exePath As String
Dim exeIcon As Icon
dirInfo = New DirectoryInfo(path_to_some_folder
'We use this For...Each to iterate over the collection of files in the folder
For Each fileInfo In dirInfo.GetFiles
'We can only find associated exes by extension, so don't show any files that have no extension
If fileInfo.Extension = String.Empty Then
Else
'Use the function to get the path to the executable for the file
exePath = GetAssociatedProgram(fileInfo.Extension)
'Use ExtractAssociatedIcon to get an icon from the path
exeIcon = Drawing.Icon.ExtractAssociatedIcon(exePath)
'Add the icon if we haven't got it already, with the executable path as the key
If ImageList1.Images.ContainsKey(exePath) Then
Else
ImageList1.Images.Add(exePath, exeIcon)
End If
'Add the file to the ListView, with the executable path as the key to the ImageList's image
ListView1.Items.Add(fileInfo.Name, exePath)
End If
Next
End Sub
GetAssociatedProgram comes from developer.com
Public Function GetAssociatedProgram(ByVal FileExtension As _
String) As String
' Returns the application associated with the specified
' FileExtension
' ie, path\denenv.exe for "VB" files
Dim objExtReg As Microsoft.Win32.RegistryKey = _
Microsoft.Win32.Registry.ClassesRoot
Dim objAppReg As Microsoft.Win32.RegistryKey = _
Microsoft.Win32.Registry.ClassesRoot
Dim strExtValue As String
Try
' Add trailing period if doesn't exist
If FileExtension.Substring(0, 1) <> "." Then _
FileExtension = "." & FileExtension
' Open registry areas containing launching app details
objExtReg = objExtReg.OpenSubKey(FileExtension.Trim)
strExtValue = objExtReg.GetValue("").ToString
objAppReg = objAppReg.OpenSubKey(strExtValue & _
"\shell\open\command")
' Parse out, tidy up and return result
Dim SplitArray() As String
SplitArray = Split(objAppReg.GetValue(Nothing).ToString, """")
If SplitArray(0).Trim.Length > 0 Then
Return SplitArray(0).Replace("%1", "")
Else
Return SplitArray(1).Replace("%1", "")
End If
Catch
Return ""
End Try
End Function
At the end of all of that, when you run this code on this folder:
alt text http://www.philippursglove.com/stackoverflow/listview1.png
you should get:
alt text http://www.philippursglove.com/stackoverflow/listview2.png
If you know the file name of the file whose icon you want, you can use the System.Drawing.Icon.ExtractAssociatedIcon function for that purpose. e.g.
Icon ico = System.Drawing.Icon.ExtractAssociatedIcon(#"C:\WINDOWS\system32\notepad.exe");
You can also refer to my answer to a related question for more implementation details.