Hola a todos!
Estoy realizando una aplicación donde el cual tiene 3 botones en donde se ejecutan diferentes comandos en cada botón a un mismo archivo (la aplicación es un convertidor). La aplicación ya esta hecha, lo que pasa es que se repite el código varias veces, entonces quisiera saber como podría hacer para que se realizo el evento click en tal botón entonces ejecutar cierto comando.
No se si me dejo entender. Pero de todas maneras adjuntaré el código completo.
pd. Mi problema también está en que no imprime en archivo de texto.
Imports System
Imports System.IO
Imports System.IO.StreamWriter
Public Class Form1
Inherits System.Windows.Forms.Form
Private Results As String
Private Delegate Sub delUpdate()
Private Finished As New delUpdate(AddressOf UpdateText)
Private Sub btnexaminar_Click(sender As Object, e As EventArgs) Handles btnexaminar.Click
Dim Dir As New FolderBrowserDialog
If Dir.ShowDialog = Windows.Forms.DialogResult.OK Then
TextBox1.Text = Dir.SelectedPath
End If
End Sub
Private Sub btndat_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btndat.Click
Dim midirectorio As String = TextBox1.Text
Dim CMDThread As New Threading.Thread(AddressOf CMDAutomate)
If midirectorio = "" Then
MessageBox.Show("Debe seleccionar la ruta donde se encuentra la data", "Error", MessageBoxButtons.OKCancel, MessageBoxIcon.Error)
Else
My.Computer.FileSystem.CopyFile("C:\Program Files\convert data\runpkr00.exe", midirectorio & "\runpkr00.exe", Microsoft.VisualBasic.FileIO.UIOption.OnlyErrorDialogs, Microsoft.VisualBasic.FileIO.UICancelOption.DoNothing)
End If
CMDThread.Start()
End Sub
Private Sub CMDAutomate()
Dim midirectorio As String = TextBox1.Text
Dim myprocess As New Process
Dim StartInfo As New System.Diagnostics.ProcessStartInfo
StartInfo.FileName = "cmd"
StartInfo.RedirectStandardInput = True
StartInfo.RedirectStandardOutput = True
StartInfo.UseShellExecute = False
StartInfo.CreateNoWindow = True
myprocess.StartInfo = StartInfo
myprocess.Start()
Dim SR As System.IO.StreamReader = myprocess.StandardOutput
Dim SW As System.IO.StreamWriter = myprocess.StandardInput
Dim comando As String
Dim cmdir As String
Dim nombre As String
For Each file As String In My.Computer.FileSystem.GetFiles(midirectorio, FileIO.SearchOption.SearchTopLevelOnly, "*.T01")
nombre = My.Computer.FileSystem.GetName(file)
cmdir = "cd " & midirectorio
comando = "runpkr00.exe -d -s " & nombre
SW.WriteLine(cmdir)
SW.WriteLine(comando)
'Results = SR.ReadToEnd
'SW.Close()
'SR.Close()
'Invoke(Finished)
MessageBox.Show("Conversión a DAT culminada." & vbNewLine & "Data: " & nombre, "Información", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1)
Next
Results = SR.ReadToEnd
SW.Close()
SR.Close()
Invoke(Finished)
End Sub
Private Sub UpdateText()
'If Me.InvokeRequired = False Then
Dim midirectorio As String = TextBox1.Text
Dim strStreamW As Stream = Nothing
Dim strStreamWriter As StreamWriter = Nothing
Dim fecha As String = DateTime.Now.ToString("dd MMM HHmmss")
Dim rutarchivo As String = String.Concat(midirectorio, "log-", fecha & ".txt")
Windows.Forms.Cursor.Current = Cursors.WaitCursor
strStreamW = File.Create(rutarchivo)
strStreamWriter = New StreamWriter(strStreamW, System.Text.Encoding.Default)
strStreamWriter.WriteLine(Results)
strStreamWriter.Close()
' Else
' Dim D As delUpdate = New delUpdate(AddressOf UpdateText)
' Me.Invoke(D)
' End If
End Sub
Private Sub btnrinex_Click(sender As System.Object, e As System.EventArgs) Handles btnrinex.Click
Dim midirectorio As String = TextBox1.Text
Dim CMD As New Threading.Thread(AddressOf CMDAutomaterin)
If midirectorio = "" Then
MessageBox.Show("Debe seleccionar la ruta donde se encuentra la data", "Error", MessageBoxButtons.OKCancel, MessageBoxIcon.Error)
Else
My.Computer.FileSystem.CopyFile("C:\Program Files\convert data\teqc.exe", midirectorio & "\teqc.exe", Microsoft.VisualBasic.FileIO.UIOption.OnlyErrorDialogs, Microsoft.VisualBasic.FileIO.UICancelOption.DoNothing)
End If
CMD.Start()
End Sub
Friend ReadOnly GPSDictionary As Dictionary(Of Integer, Integer) = Me.GetGPSDictionary
Private Function GetGPSDictionary() As Dictionary(Of Integer, Integer)
Dim ThisYear As Integer = Now.Year
Dim DaysInThisYear As Integer = (From month As Integer In Enumerable.Range(1, 12)
Select DateTime.DaysInMonth(ThisYear, month)).Sum
Dim GPSWeeks As IEnumerable(Of Integer) = Enumerable.Range(1773 - 1, 1825)
Dim Result As New Dictionary(Of Integer, Integer)
For Day As Integer = 1 To DaysInThisYear
Result.Add(Day, GPSWeeks(DatePart(DateInterval.WeekOfYear,
New DateTime(ThisYear, 1, 1).AddDays(Day - 1))))
Next Day
Return Result
End Function
Private Sub CMDAutomaterin()
Dim midirectorio As String = TextBox1.Text
Dim myprocess As New Process
Dim StartInfo As New System.Diagnostics.ProcessStartInfo
StartInfo.FileName = "cmd"
StartInfo.RedirectStandardInput = True
StartInfo.RedirectStandardOutput = True
StartInfo.UseShellExecute = False
StartInfo.CreateNoWindow = True
myprocess.StartInfo = StartInfo
myprocess.Start()
Dim SR As System.IO.StreamReader = myprocess.StandardOutput
Dim SW As System.IO.StreamWriter = myprocess.StandardInput
Dim comandodat As String
Dim comandorin As String
Dim cmdir As String
Dim nombre As String
Dim renombre As String
For Each file As String In My.Computer.FileSystem.GetFiles(midirectorio, FileIO.SearchOption.SearchTopLevelOnly, "*.T01")
nombre = Path.GetFileNameWithoutExtension(file)
renombre = Microsoft.VisualBasic.Left(nombre, Len(nombre) - 2) & "0"
Dim DayOfYear As Integer = Mid(nombre, 5, 3)
Dim semgps As Integer = Me.GPSDictionary(DayOfYear)
cmdir = "cd " & midirectorio
comandodat = "runpkr00.exe -g -d " & nombre & ".t01"
comandorin = "teqc.exe +nav " & renombre & ".14n -O.int 5 -O.dec 5 -O.ag IGN-PERU -O.o CPG -week " & semgps & " -tr d " & nombre & ".tgd> " & renombre & ".14o"
SW.WriteLine(cmdir)
SW.WriteLine(comandodat)
SW.WriteLine(comandorin)
'Results = SR.ReadToEnd
' SW.Close()
'SR.Close()
'Invoke(Finished)
MessageBox.Show("Conversión a RINEX culminada." & vbNewLine & "Data: " & nombre, "Información", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1)
Next
Results = SR.ReadToEnd
SW.Close()
SR.Close()
Invoke(Finished)
End Sub
Private Sub btntqc_Click(sender As Object, e As EventArgs) Handles btntqc.Click
Dim midirectorio As String = TextBox1.Text
Dim CMD As New Threading.Thread(AddressOf CMDAutomateqc)
If midirectorio = "" Then
MessageBox.Show("Debe seleccionar la ruta donde se encuentra la data", "Error", MessageBoxButtons.OKCancel, MessageBoxIcon.Error)
Else
My.Computer.FileSystem.CopyFile("C:\Program Files\convert data\teqc.exe", midirectorio & "\teqc.exe", Microsoft.VisualBasic.FileIO.UIOption.OnlyErrorDialogs, Microsoft.VisualBasic.FileIO.UICancelOption.DoNothing)
End If
CMD.Start()
End Sub
Private Sub CMDAutomateqc()
Dim midirectorio As String = TextBox1.Text
Dim myprocess As New Process
Dim StartInfo As New System.Diagnostics.ProcessStartInfo
StartInfo.FileName = "cmd"
StartInfo.RedirectStandardInput = True
StartInfo.RedirectStandardOutput = True
StartInfo.UseShellExecute = False
StartInfo.CreateNoWindow = True
myprocess.StartInfo = StartInfo
myprocess.Start()
Dim SR As System.IO.StreamReader = myprocess.StandardOutput
Dim SW As System.IO.StreamWriter = myprocess.StandardInput
Dim comandorin As String
Dim cmdir As String
Dim nombre As String
Dim renombre As String
For Each file As String In My.Computer.FileSystem.GetFiles(midirectorio, FileIO.SearchOption.SearchTopLevelOnly, "*.T01")
nombre = Path.GetFileNameWithoutExtension(file)
renombre = Microsoft.VisualBasic.Left(nombre, Len(nombre) - 2) & "0"
If System.IO.File.Exists(midirectorio & "\" & renombre & ".14n") And System.IO.File.Exists(midirectorio & "\" & renombre & ".14o") Then
cmdir = "cd " & midirectorio
comandorin = "teqc.exe -nav " & renombre & ".14n +qc " & renombre & ".14o"
SW.WriteLine(cmdir)
SW.WriteLine(comandorin)
'Results = SR.ReadToEnd
'SW.Close()
'SR.Close()
'Invoke(Finished)
MessageBox.Show("Quality Check." & vbNewLine & "Data: " & nombre, "Información", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1)
Else
MessageBox.Show("Se necesitan de los archivos RINEX (14n y 14o)" & vbNewLine & "Solución: Clic en el Botón RINEX.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1)
End If
Next
Results = SR.ReadToEnd
SW.Close()
SR.Close()
Invoke(Finished)
End Sub
1. No estás liberando el FolderBrowserDialog que instancias.
Private Sub btnexaminar_Click(sender As Object, e As EventArgs) Handles btnexaminar.Click
Using Dir As New FolderBrowserDialog
If Dir.ShowDialog = DialogResult.OK Then
TextBox1.Text = Dir.SelectedPath
End If
End Using
End Sub
2. Reducción de código de Botones:
Private CMDThread As Threading.Thread = Nothing
Friend ReadOnly Property MiDirectorio As String
Get
Return TextBox1.Text
End Get
End Property
Private Sub btndat_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btndat.Click
Me.CMDThread = New Threading.Thread(AddressOf Me.CMDAutomate)
Me.CopyFile("C:\Program Files\convert data\runpkr00.exe", IO.Path.Combine(Me.MiDirectorio, "\runpkr00.exe"))
CMDThread.Start()
End Sub
Private Sub btnrinex_Click(sender As Object, e As EventArgs) Handles btnrinex.Click
Me.CMDThread = New Threading.Thread(AddressOf Me.CMDAutomaterin)
Me.CopyFile("C:\Program Files\convert data\teqc.exe", IO.Path.Combine(Me.MiDirectorio, "\teqc.exe"))
Me.CMDThread.Start()
End Sub
Private Sub btntqc_Click(sender As Object, e As EventArgs) Handles btntqc.Click
Me.CMDThread = New Threading.Thread(AddressOf Me.CMDAutomateqc)
Me.CopyFile("C:\Program Files\convert data\teqc.exe", IO.Path.Combine(Me.MiDirectorio, "\teqc.exe"))
Me.CMDThread.Start()
End Sub
Private Sub CopyFile(ByVal sourcefile As String, ByVal destinationfile As String)
If String.IsNullOrEmpty(Me.MiDirectorio) Then
MessageBox.Show("Debe seleccionar la ruta donde se encuentra la data", "Error",
MessageBoxButtons.OKCancel, MessageBoxIcon.Error)
Else
My.Computer.FileSystem.CopyFile(sourcefile, destinationfile,
FileIO.UIOption.OnlyErrorDialogs,
FileIO.UICancelOption.DoNothing)
End If
End Sub
3. Reducción de código de Procesos
Eliminar todo esto repetido:
Dim myprocess As New Process
Dim StartInfo As New System.Diagnostics.ProcessStartInfo
StartInfo.FileName = "cmd"
StartInfo.RedirectStandardInput = True
StartInfo.RedirectStandardOutput = True
StartInfo.UseShellExecute = False
StartInfo.CreateNoWindow = True
myprocess.StartInfo = StartInfo
por:
Friend MyProcess As New Process With
{
.StartInfo = New ProcessStartInfo With
{
.FileName = "cmd",
.RedirectStandardInput = True,
.RedirectStandardOutput = True,
.UseShellExecute = False,
.CreateNoWindow = True
}
}
PD: Aun se puede simplificar más, tanto los botones como las tareas de los threads, pero creo que con eso ya te basta :P.
Saludos