Fileopen through the FolderBrowserDialog.. How?? HELP! - vb.net

This is what i got now...
FolderBrowserDialog1.ShowDialog()
TextBox1.Text = FolderBrowserDialog1.SelectedPath
If FolderBrowserDialog1.SelectedPath = Nothing = True Then MsgBox("Select your folder..")
If FolderBrowserDialog1.SelectedPath = Nothing = True Then Button1.Enabled = False
If FolderBrowserDialog1.SelectedPath = Nothing = False Then Button1.Enabled = True
End Sub
FileOpen(1, ,,,,,, & "File" & ".dll", OpenMode.Output)
PrintLine(1, TextBox2.Text)
FileClose()
End Sub
But i want the Output folder (The place where File.dll is saved) to be the FolderBrowserDialog1.SelectedPath... how? Anyone?
Tried FileOpen(1, FolderBrowserDialog1.SelectedPath & File & .dll, OpenMode.Output) but no :(

Note sure I understand what you want to do, but you may try to set the SelectedPath property before calling ShowDialog method.

Related

Progress bar is not working in BackgroundWorker VB.Net

I'm trying to get a progress bar to show while a method is being executed. I've called BackgroundWorker1.RunWorkerAsync() from a button. Then in the DoWork I call the method to run "runCopyFiles". I update the progress in ProgressChanged, and exit with RunWorkerCompleted. I'm not sure what I have wrong. I've searched the net for tutorials and examples on how to do this and have created the code from them. But the progress bar doesn't show.
Code For executing from button
Private Sub btnExecuteFileCopy_Click(sender As Object, e As EventArgs) Handles btnExecuteFileCopy.Click
Me.Refresh()
If Not BackgroundWorker1.IsBusy = True Then
BackgroundWorker1.RunWorkerAsync()
End If
End Sub
Code for BackGroundWorker
Private Sub BackgroundWorker1_DoWork(sender As Object, e As ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
BackgroundWorker1.WorkerReportsProgress = True
Const Max As Integer = 1000
For i = 1 To Max
'' do something
'' (I put a sleep to simulate time consumed)
Threading.Thread.Sleep(100)
'' report progress at regular intervals
BackgroundWorker1.ReportProgress(CInt(100 * i / Max), "Running..." & i.ToString)
'' check at regular intervals for CancellationPending
If BackgroundWorker1.CancellationPending Then
BackgroundWorker1.ReportProgress(CInt(100 * i / Max), "Cancelling...")
Exit For
End If
Next
runCopyFiles()
End Sub
Private Sub BackgroundWorker1_ProgressChanged(sender As Object, e As ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
ProgressBar1.Value = e.ProgressPercentage
lblStatus.Text = e.ProgressPercentage.ToString() + " %"
End Sub
Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
If e.Cancelled = True Then
MsgBox(" Operation Cancelled ")
ProgressBar1.Value = 0
lblStatus.Text = ""
ElseIf e.Error IsNot Nothing Then
MsgBox(e.Error.Message)
Else
MsgBox(" Process Complete ")
End If
End Sub
Code RunCopy
Private Sub runCopyFiles()
Application.UseWaitCursor = True
Application.DoEvents()
Me.Refresh()
Dim sFileToFind As String
Dim location As String
Dim File As String
'Dim createReportFldr As String
'Dim createXMLFldr As String
'Dim createImgFldr As String
'Directory Files are located in
location = txtFolderPath.Text
'Directory files are to copied into
MoveLocation = CopyToPath
createImgFldr = MoveLocation & "\Figures"
createReportFldr = MoveLocation & "\Reports"
createXMLFldr = MoveLocation & "\XML files"
'Create Figures Folder
If Not IO.Directory.Exists(createImgFldr) Then
IO.Directory.CreateDirectory(createImgFldr)
' MsgBox("folder created" & createFolder)
End If
'Create Reports folder
If Not IO.Directory.Exists(createReportFldr) Then
IO.Directory.CreateDirectory(createReportFldr)
'MsgBox("folder created" & createReportFldr)
End If
'Create XML folder
If Not IO.Directory.Exists(createXMLFldr) Then
IO.Directory.CreateDirectory(createXMLFldr)
' MsgBox("folder created" & createFolder)
End If
orphanedFiles = MoveLocation & "\Reports\OrphanedFilesItems.txt"
' Create or overwrite the file.
System.IO.File.Create(orphanedFiles).Dispose()
ListofFiles = MoveLocation & "\Reports\ListOfFiles.txt"
' Create or overwrite the file.
System.IO.File.Create(ListofFiles).Dispose()
MissingFiles = MoveLocation & "\Reports\MissingGraphicList.txt"
' Create or overwrite the file.
System.IO.File.Create(MissingFiles).Dispose()
Dim FILE_NAME As String
FILE_NAME = txtFileName.Text
Dim objReader As New System.IO.StreamReader(FILE_NAME)
Dim sFile As String
Do While objReader.Peek() <> -1
File = objReader.ReadLine()
sFileToFind = location & "\" & File & "*.*"
sFile = File
Dim paths() As String = IO.Directory.GetFiles(location, sFile, IO.SearchOption.AllDirectories)
If paths.Count = 0 Then
System.IO.File.AppendAllText(orphanedFiles, sFile & vbNewLine)
' Debug.Print(File)
'If System.IO.File.Exists(orphanedFiles) = True Then
' Dim objWriter As New System.IO.StreamWriter(orphanedFiles, IO.FileMode.Append)
' objWriter.WriteLine(File)
' objWriter.Close()
'Else
'MsgBox("Creating Orphaned File Now. ")
'End If
Else
For Each pathAndFileName As String In paths
Dim moveToFolder As String
If System.IO.File.Exists(pathAndFileName) = True Then
Dim sRegLast As String = pathAndFileName.Substring(pathAndFileName.LastIndexOf("\") + 1)
Dim toFileLoc As String
'MsgBox("sRegLast " & sRegLast)
' fileLoc = MoveLocation & sRegLast
moveToFolder = MoveLocation & "\XML files\" & sRegLast
toFileLoc = createXMLFldr & "\" & sRegLast
'MsgBox("FileLoc " & fileLoc)
'if toFileLoc = XML file exists move it into the XML files folder
If System.IO.File.Exists(toFileLoc) = False Then
System.IO.File.Copy(pathAndFileName, moveToFolder)
System.IO.File.AppendAllText(ListofFiles, sRegLast & vbNewLine)
End If
End If
Next
End If
Loop
'MsgBox("Files have been moved")
Call CreateGraphicsFunction(Nothing, System.EventArgs.Empty)
Call getImages()
MsgBox("Process Complete", MsgBoxStyle.DefaultButton1)
Application.UseWaitCursor = False
Application.DoEvents()
' Me.Close()
End Sub
If you loop while there are more lines in your file, there's no way to know how many total lines there are, and that is a crucial component in the percent calculation for the progress bar:
percent = 100 * currentFile / totalFiles
So instead, we can read all lines up front and iterate over them. This should be your runCopyFiles
Dim fileNames = System.IO.File.ReadAllLines(FILE_NAME)
For i = 0 To fileNames.Count() - 1
Dim fileName = fileNames(i)
sFileToFind = location & "\" & fileName & "*.*"
Dim paths = IO.Directory.GetFiles(location, fileName, IO.SearchOption.AllDirectories)
If Not paths.Any() Then
System.IO.File.AppendAllText(orphanedFiles, fileName & vbNewLine)
Else
For Each pathAndFileName As String In paths
If System.IO.File.Exists(pathAndFileName) = True Then
Dim sRegLast = pathAndFileName.Substring(pathAndFileName.LastIndexOf("\") + 1)
Dim toFileLoc = System.IO.Path.Combine(createXMLFldr, sRegLast)
Dim moveToFolder = System.IO.Path.Combine(moveLocation, "XML files", sRegLast)
'if toFileLoc = XML file exists move it into the XML files folder
If System.IO.File.Exists(toFileLoc) = False Then
System.IO.File.Copy(pathAndFileName, moveToFolder)
System.IO.File.AppendAllText(ListofFiles, sRegLast & vbNewLine)
End If
End If
Next
End If
BackgroundWorker1.ReportProgress(100 * i / fileNames.Count())
Next
That is where the progress should be reported.
And all you should have in your DoWork is this
Private Sub BackgroundWorker1_DoWork(sender As Object, e As ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
runCopyFiles()
End Sub
You never need Application.DoEvents, and if you find that you do need it, then you are doing something wrong. DoWork calls code on a background thread which
Shouldn't access the UI without invoking calls on the UI thread
In turn doesn't block the UI from updating...
... which is really why you use it - so you can run processing code behind the UI without slowing it down.
In total, here are all the things you should remember to do
Don't access UI from background thread
Use Using to automatically dispose IDisposable objects
Use System.IO.Path.Combine to combine paths instead of using string concatenation
Don't call runCopyFiles 101 times
BackgroundWorker1.ReportProgress is meant to be called when you are doing work
If booleanValue = True Then is redundant, just do If booleanValue Then

How to implement multiple catches with error provider if textbox is empty

I have a program that writes txtboxes to a .txt file, I don't want to be able to "Generate Log Book Entry" until all text boxes are filled in and all check boxes are checked. I have the error provider to pop up correctly, but I need it implemented in the code so that it works the same way as the check boxes (All checkboxes must be checked before you're able to generate log book entry).
'Aircraft make/model textbox cannot be blank
If Me.TextBox4.Text = "" Then
ErrorProvider1.SetError(TextBox4, "Cannot be blank")
Else
Me.ErrorProvider1.SetError(Me.TextBox4, "")
End If
'N-number textbox cannot be blank
If Me.TextBox3.Text = "" Then
ErrorProvider1.SetError(TextBox3, "Cannot be blank")
Else
Me.ErrorProvider1.SetError(Me.TextBox3, "")
End If
'If all checkboxes are checked then no error is shown; if a single checkbox is not check, errorprovider shown
If CheckBox1.Checked And CheckBox2.Checked And CheckBox3.Checked And CheckBox4.Checked And CheckBox5.Checked And CheckBox6.Checked And CheckBox7.Checked Then
ErrorProvider1.SetError(Button2, "")
Dim FILE_NAME As String = "C:\Users\Blake\Documents\test2.txt" 'Sends information to test2.txt
If System.IO.File.Exists(FILE_NAME) = True Then
Dim objWriter As New System.IO.StreamWriter(FILE_NAME)
objWriter.Write("Aircraft Make & Model: " & TextBox4.Text & ", N-number: " & TextBox3.Text)
objWriter.Write("
Gascolator Removed & Inspected in accordance with FAA approved maintenance manual")
objWriter.Write("
Signature _____________________________")
objWriter.Write(" " & DateTime.Now) 'Displays current date and time
objWriter.Close()
MsgBox("Text Written To File")
Else
MsgBox("File Does Not Exist")
End If
Else ErrorProvider1.SetError(Button2, "All boxes must be checked")
End If
I have tried moving
Me.ErrorProvider1.SetError(Me.TextBox4, "")
End If
but it doesn't allow more than one "If" statement in that section of code.enter image description here
Doesn't allow text to be written to file bc/ txtboxes are not checked
Blank boxes able to write in .txt file
Entered info with .txtfile
Try restructuring your code like this
If Me.TextBox4.Text = "" Then
ErrorProvider1.SetError(TextBox4, "Cannot be blank")
Else
Me.ErrorProvider1.SetError(Me.TextBox4, "")
End If
If Me.TextBox3.Text = "" Then
ErrorProvider1.SetError(TextBox3, "Cannot be blank")
Else
Me.ErrorProvider1.SetError(Me.TextBox3, "")
'Add this line here
validateCheckBoxes()
End If
Sub validateCheckBoxes()
'Move this part here
If CheckBox1.Checked And CheckBox2.Checked And CheckBox3.Checked And CheckBox4.Checked And CheckBox5.Checked And CheckBox6.Checked And CheckBox7.Checked Then
ErrorProvider1.SetError(Button2, "")
Dim FILE_NAME As String = "C:\Users\Blake\Documents\test2.txt" 'Sends information to test2.txt
If System.IO.File.Exists(FILE_NAME) = True Then
Dim objWriter As New System.IO.StreamWriter(FILE_NAME)
objWriter.Write("Aircraft Make & Model: " & TextBox4.Text & ", N-number: " & TextBox3.Text)
objWriter.Write("Gascolator Removed & Inspected in accordance with FAA approved maintenance manual")
objWriter.Write("Signature _____________________________")
objWriter.Write(" " & DateTime.Now)
'Displays current date and time
objWriter.Close()
MsgBox("Text Written To File")
Else
MsgBox("File Does Not Exist")
End If
Else
ErrorProvider1.SetError(Button2, "All boxes must be checked")
End If
End Sub
While the way you did this will eventually work, I would suggest another approach.
There is like a bazillion ways to do this. I would simply disable the "Generate Log" button until the user has checked and filled everything. This would prevent most problems you mentioned, but you wouldn't have the nice error messages I read through your code, so if they are important you won't be able to work this way.
Here's a code snippet that would do just what I just spoke about:
'Check if the user is checking boxes
Private Sub Checkboxes_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox1.CheckedChanged, CheckBox2.CheckedChanged, CheckBox3.CheckedChanged, CheckBox4.CheckedChanged, CheckBox5.CheckedChanged, CheckBox6.CheckedChanged, CheckBox7.CheckedChanged
UpdateGenerateLogButtonEnabled()
End Sub
'Check if the user is writing text
Private Sub TextBoxes_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged, TextBox2.TextChanged
UpdateGenerateLogButtonEnabled()
End Sub
'Manage the GenerateLog button Enabled state
Private Sub UpdateGenerateLogButtonEnabled()
GenerateLogBookButton.Enabled = CheckBox1.Checked AndAlso CheckBox2.Checked AndAlso CheckBox3.Checked AndAlso CheckBox4.Checked AndAlso CheckBox5.Checked AndAlso CheckBox6.Checked AndAlso CheckBox7.Checked AndAlso Not TextBox1.Text = "" AndAlso Not TextBox2.Text = ""
End Sub
As I stated, there are many, many ways to validate this kind of code. If you need your error messages, you'll want a different one. Either way, have fun!

Command Prompt Batchfile output to VB textbox

I have a number of batch files and I'm trying to wrap a GUI around them so they are easily available for some of my users all in one place.
At the moment, I've got 2 buttons and a Textbox. Each button calls the same batch file with a different working directory (though in production, the batch files will be different). At the moment, all it does is call 'DIR /A /B" to list a directory contents.
DIR /A /B
exit
I've got the following code: (Button 2 is identical, but with a different working directory)
Public Class Form1
Dim P As New Process
Dim SW As System.IO.StreamWriter
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
AddHandler P.OutputDataReceived, AddressOf DisplayOutput
P.StartInfo.CreateNoWindow() = True
P.StartInfo.UseShellExecute = False
P.StartInfo.WorkingDirectory = "C:\temp"
P.StartInfo.RedirectStandardInput = True
P.StartInfo.RedirectStandardOutput = True
P.StartInfo.RedirectStandardError = True
P.StartInfo.FileName = "c:\temp\dircmd.cmd"
P.Start()
P.SynchronizingObject = TextBox1
Try
P.BeginOutputReadLine()
TextBox1.Text = TextBox1.Text & vbCrLf & "Begin output" & vbCrLf
SW = P.StandardInput
SW.WriteLine()
MsgBox("WriteLine()")
SW.Dispose()
SW.Close()
MsgBox("StreamWriter Close")
P.WaitForExit()
P.CancelOutputRead()
P.Close()
MsgBox("Process Close")
Catch ex As Exception
MsgBox(ex.ToString())
End Try
End Sub
Private Sub DisplayOutput(ByVal sendingProcess As Object, ByVal output As DataReceivedEventArgs)
Textbox1.AppendText(output.Data() & vbCrLf)
End Sub
My problem is that I'm getting the output from each command, however its getting duplicated. First button, first time works fine. Second button works, but everything is listed twice. Going back to first button, everything is listed 3 times. I initially thought I needed to clear the StreamWriter buffer, but its not repeating old info, its just repeating new info and I'm not sure why.
Begin output
C:\temp>DIR /A /B
bob.txt
dircmd.cmd
LocationRouting.xml
TempFrogsareNOTCool.txt
Test.txt
test2.txt
Test3.txt
C:\temp>exit
Begin output 2
C:\>DIR /A /B
C:\>DIR /A /B
$Recycle.Bin
$Recycle.Bin
Config.Msi
Config.Msi
Documents and Settings
Documents and Settings
<snip>
C:\>exit
C:\>exit
Switch to using a Using construct to instantiate and dispose of the Process:
Option A:
Using P As Process = New Process
P.StartInfo.CreateNoWindow = True
P.StartInfo.UseShellExecute = False
P.StartInfo.WorkingDirectory = "C:\temp"
P.StartInfo.RedirectStandardInput = True
P.StartInfo.RedirectStandardOutput = True
P.StartInfo.RedirectStandardError = True
P.StartInfo.FileName = "c:\temp\dircmd.cmd"
P.Start()
Dim sOutput As String
Using oStreamReader As System.IO.StreamReader = P.StandardOutput
sOutput = oStreamReader.ReadToEnd()
End Using
OutputTextBox.Text = sOutput
P.Close()
End Using
Option B:
Private Sub TestDirOutputButton_Click(sender As System.Object, e As System.EventArgs) Handles TestDirOutputButton.Click
Using P As Process = New Process
AddHandler P.OutputDataReceived, AddressOf DisplayOutput
P.StartInfo.CreateNoWindow() = True
P.StartInfo.UseShellExecute = False
P.StartInfo.WorkingDirectory = "C:\temp"
P.StartInfo.RedirectStandardInput = True
P.StartInfo.RedirectStandardOutput = True
P.StartInfo.RedirectStandardError = True
P.StartInfo.FileName = "c:\temp\dircmd.cmd"
P.Start()
P.SynchronizingObject = OutputTextBox
Try
P.BeginOutputReadLine()
OutputTextBox.Text = OutputTextBox.Text & vbCrLf & "Begin output" & vbCrLf
SW = P.StandardInput
SW.WriteLine()
MsgBox("WriteLine()")
SW.Dispose()
SW.Close()
MsgBox("StreamWriter Close")
P.WaitForExit()
P.CancelOutputRead()
P.Close()
MsgBox("Process Close")
Catch ex As Exception
MsgBox(ex.ToString())
End Try
RemoveHandler P.OutputDataReceived, AddressOf DisplayOutput
End Using
End Sub

FolderBrowserDialog open again on cancel

When i open the FolderBrowserDialog then click cancel it reopens again.
But, On the second FolderBrowserDialog when you click cancel again it properly closes.
And when you select a path on the second FolderBrowserDialog, It does or returns nothing
Can i stop the second FolderBrowserDialog on appearing when i click on cancel on the first?
I dont know why is it appearing. thanks in advance.
here is my code:
Dim apppath
Try
FolderBrowserDialog1.RootFolder = Environment.SpecialFolder.Desktop
FolderBrowserDialog1.SelectedPath = "C:\"
FolderBrowserDialog1.Description = "Select File Location Path"
If FolderBrowserDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
apppath = FolderBrowserDialog1.SelectedPath
ElseIf FolderBrowserDialog1.ShowDialog() = Windows.Forms.DialogResult.Cancel Then
Exit Sub
End If
My.Computer.FileSystem.WriteAllText(apppath & "apppath.txt", apppath, False)
MessageBox.Show(apppath)
Catch ex As Exception
MessageBox.Show("Invalid Location")
Exit Sub
End Try
Try something like this
Dim result as Windows.Forms.DialogResult = FolderBrowserDialog1.ShowDialog()
If result = Windows.Forms.DialogResult.OK Then
apppath = FolderBrowserDialog1.SelectedPath
ElseIf result = Windows.Forms.DialogResult.Cancel Then
Exit Sub
End If

VB.net Problems with Openfiledialog

I'm making this music player thing and I need help with some coding. I want my program to play a certain file when Checkbox1 is checked. I'm using OpenFileDialog but i'm not sure that's the right thing to do. I can't get it to work. Here's my code:
If CheckBox1.Checked = True Then
OpenFileDialog1.OpenFile()
AxWindowsMediaPlayer1.URL = OpenFileDialog1.FileName
AxWindowsMediaPlayer1.Ctlcontrols.play()
ElseIf CheckBox1.Checked = False Then
AxWindowsMediaPlayer1.Ctlcontrols.stop()
End If
Can someone please help me?
You need to show the dialog:
If CheckBox1.Checked Then
If OpenFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
AxWindowsMediaPlayer1.URL = OpenFileDialog1.FileName
AxWindowsMediaPlayer1.Ctlcontrols.Play()
End If
Else
AxWindowsMediaPlayer1.Ctlcontrols.Stop()
End If
If you want the dialog to display so the user can select a file, use ShowDialog() and check the return value to ensure a file was actually selected by the user:
If CheckBox1.Checked = True Then
If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
AxWindowsMediaPlayer1.URL = OpenFileDialog1.FileName
AxWindowsMediaPlayer1.Ctlcontrols.play()
End If
ElseIf CheckBox1.Checked = False Then
AxWindowsMediaPlayer1.Ctlcontrols.stop()
End If