how to send the output to a logfile and richtextbox - vb.net

I have the follow code that works for sending the output to a richtextbox. I cant figure out how to also have the output sent to a log file if I choose as well. this is the beginnings of my code for choosing to log the output. I cant figure out how to get it to log the output to the file location.
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
If (OpenFileDialog1.ShowDialog() = DialogResult.OK) Then
TextBox31.Text = Chr(34) & OpenFileDialog1.FileName & Chr(34)
End If
End Sub
here is my working code for displaying the output in the richtextbox.
Private Sub ExecuteButton_Click(sender As Object, e As EventArgs) Handles ExecuteButton.Click
System.Windows.Forms.Application.DoEvents()
Dim myprocess As New Process
Dim startinfo As New ProcessStartInfo(TextBox3.Text, TextBox1.Text) With {
.UseShellExecute = False,
.RedirectStandardOutput = True,
.CreateNoWindow = True
}
myprocess.StartInfo = startinfo
myprocess.Start()
Dim str1 As String = ""
Using MyStreamReader As IO.StreamReader = myprocess.StandardOutput
str1 &= MyStreamReader.ReadToEnd
End Using
RichTextBox1.Text = str1
End Sub
Note: This is what I used to be able to log the output
If CheckBox34.Checked = True Then
Dim objWriter As New System.IO.StreamWriter(TextBox31.Text & "\" & Format(Now, "dd-MMM-yyyy") & ".log", True)
objWriter.WriteLine(Format(Now, "dd-MMM-yyyy HH:mm:ss ") & TextBox4.Text & vbCrLf & str1)
objWriter.Close()
End If

Try With this sample:
Dim MyPath = "C:\MyLog.Log"
FileOpen(1, MyPath, OpenMode.Append)
Dim lNumberofRecs = LOF(1)
Print(1, Format(Now, "dd-MMM-yyyy HH:mm:ss") & "#Import Begin" & vbCrLf)
FileClose(1)
or with this:
Dim objWriter As New System.IO.StreamWriter("C:\MyData\mylog.log", True)
objWriter.WriteLine("each log data you have")
objWriter.Close()

Related

File can't be accessed because it's already in use

I have a Sub that reads a file that was created in another Sub. I'm getting an error
Can't access file in use in other process
From what I've read on the net I need to close the StreamReader. I've tried to use .close() on different variables, but nothing seems to work.
Below is the code that writes the file the other Sub then accesses.
Private Sub CreateGraphicsFunction(sender As Object, e As EventArgs)
Dim Regex = New Regex("infoEntityIdent=""(ICN.+?)[""].*?[>]")
strGraphicFile = MoveLocation & "\ICN-LIST.txt"
Dim ICNFiles = Directory.EnumerateFiles(MovePath, "*.*", SearchOption.AllDirectories)
For Each tFile In ICNFiles
Dim input = File.ReadAllText(tFile)
Dim match = Regex.Match(input)
If match.Success Then
output.Add(match.Groups(1).Value)
End If
Next
File.WriteAllLines(strGraphicFile, output)
locationGraphicsLog = strGraphicFile
End Sub
The other Sub that reads the file created
Private Sub btnFindICN_Click(sender As Object, e As EventArgs) Handles btnFindICN.Click
Application.UseWaitCursor = True
Application.DoEvents()
Me.Refresh()
Dim sGraphicFilesToFind As String
Dim graphicLocation As String
'MoveWithPath As String
Dim graphicFile As String
graphicLocation = txtSearchICN.Text
MoveLocation = MovePath
graphicLogFile = MoveLocation & "\Reports\1-OrphanedFilesItems.txt"
Dim FILE_NAME As String
FILE_NAME = MoveLocation & "\ICN-LIST.txt"
Dim objReader As New System.IO.StreamReader(FILE_NAME)
Dim sGraphicFile As String
Do While objReader.Peek() <> -1
graphicFile = objReader.ReadLine()
sGraphicFilesToFind = graphicLocation & "\" & graphicFile & "*.*"
sGraphicFile = graphicFile
Dim createGraphicReportFldr As String
Dim paths() As String = IO.Directory.GetFiles(graphicLocation, sGraphicFile, IO.SearchOption.AllDirectories)
If paths.Count = 0 Then
'Debug.Print(graphicFile)
If System.IO.File.Exists(graphicLogFile) = True Then
Dim objWriter As New System.IO.StreamWriter(graphicLogFile, IO.FileMode.Append)
objWriter.WriteLine(graphicFile)
objWriter.Close()
Else
'MsgBox("Creating Orphaned graphicFile Now. ")
createGraphicReportFldr = MoveLocation & "\Reports"
If Not IO.Directory.Exists(createGraphicReportFldr) Then
IO.Directory.CreateDirectory(createGraphicReportFldr)
'MsgBox("folder created" & createGraphicReportFldr)
Dim writeFile As IO.StreamWriter
writeFile = IO.File.CreateText(graphicLogFile)
writeFile.Write(graphicFile & vbCrLf)
writeFile.Close()
Else
'MsgBox("Folder already exist")
End If
End If
Else
For Each pathAndFileName As String In paths
Dim createGraphicsFolder As String
'Dim moveFileToNewFolder As String
If System.IO.File.Exists(pathAndFileName) = True Then
Dim sRegLast As String = pathAndFileName.Substring(pathAndFileName.LastIndexOf("\") + 1)
Dim toGraphiicFileLocation As String
'MsgBox("sRegLast " & sRegLast)
fileGraphicLoc = MoveLocation & sRegLast
createGraphicsFolder = MoveLocation & "\Figures"
moveGraphicFileToNewFolder = MoveLocation & "\Figures\" & sRegLast
toGraphiicFileLocation = createGraphicsFolder & "\" & sRegLast
'MsgBox("FileLoc " & fileLoc)
If Not IO.Directory.Exists(createGraphicsFolder) Then
IO.Directory.CreateDirectory(createGraphicsFolder)
' MsgBox("folder created" & createGraphicsFolder)
End If
If System.IO.File.Exists(fileGraphicLoc) = False Then
System.IO.File.Copy(pathAndFileName, moveGraphicFileToNewFolder)
Debug.Write("Graphics moved to : " & moveGraphicFileToNewFolder & vbCrLf)
End If
End If
Next
End If
Loop
'MsgBox("graphicFiles have been moved")
Call CreateGraphicsFunction(Nothing, System.EventArgs.Empty)
Application.UseWaitCursor = False
Application.DoEvents()
' Me.Close()
End Sub
In the "other Sub", change
Dim objReader As New System.IO.StreamReader(FILE_NAME)
to
Using objReader = New System.IO.StreamReader(FILE_NAME)
and add End Using where you are done with it. Probably right after Loop. This will ensure that the disposable stream is always disposed.
See Using Statement (Visual Basic). You almost always want to wrap an IDisposable object in a Using block if you are able to restrict its scope to a single method.

.DrawToBitmap Saved Image Wont Open In IE Browser

The code below saves a populated form as a .JPG image. However, it needs to be able to be opened in IE browser. Any other .JPG image not generated by the code opens and if I change the code to save as a .png it also opens in IE browser. Do I need to do anything special for .JPG/ .JPEG?
Code:
Private Sub btnImage_Click(sender As Object, e As EventArgs) Handles btnImage.Click
Dim dialog As New FolderBrowserDialog()
dialog.RootFolder = Environment.SpecialFolder.Desktop
dialog.SelectedPath = ""
dialog.Description = "Select Save Location"
If dialog.ShowDialog() = DialogResult.OK Then
Savepath = dialog.SelectedPath
SaveName = txtPN.Text
If Not SaveName = "" Then
Using bm As New Bitmap(HUD.pnlMain.Width, HUD.pnlMain.Height, Imaging.PixelFormat.Format16bppRgb555)
HUD.pnlMain.DrawToBitmap(bm, New Rectangle(0, 0, bm.Width, bm.Height))
bm.Save(Savepath & "\" & SaveName & ".JPG") '.PNG
End Using
MsgBox("Image was saved as " & SaveName & " at " & Savepath)
Else
Exit Sub
End If
Exit Sub
End If
End Sub
I get this:
Maybe you should try passing the format.
bm.Save(Savepath & "\" & SaveName & ".JPG", System.Drawing.Imaging.ImageFormat.Jpeg)
Also, you could use the Path class to create the full path of the file.

How can I export the datagridview to .csv without headers?

My csv file is like this
There is no blank spaces or whatsoever.
The problem as you can see is that I do not know how to export my datagridview as .csv excluding column headers.
This is how I have done my export code:
Private Sub IncomeToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles IncomeToolStripMenuItem.Click
Dim saveFileDialog1 As New SaveFileDialog()
saveFileDialog1.Filter = "CSV|*.csv"
saveFileDialog1.RestoreDirectory = True
If saveFileDialog1.ShowDialog() = DialogResult.OK Then
Dim incomefile As String = String.Empty
For Each column As DataGridViewColumn In Expense.Columns
incomefile = incomefile & column.HeaderText & ","
Next
incomefile = incomefile.TrimEnd(",")
incomefile = incomefile & vbCr & vbLf
For Each row As DataGridViewRow In Expense.Rows
For Each cell As DataGridViewCell In row.Cells
incomefile = incomefile & cell.FormattedValue.replace(",", "") & ","
Next
incomefile = incomefile.TrimEnd(",")
incomefile = incomefile & vbCr & vbLf
Next
System.IO.File.WriteAllText(saveFileDialog1.FileName, incomefile)
End If
Dim msg1 = "Export Successful"
Dim title = "Excel Export"
MsgBox(msg1, , title)
End Sub
Please advise me. Some others mentioned that I'd better off use datatable to export it, but since I started to learn computer programming 43 hours ago, I have no clue on how to declare the data i have put in my datagridview and export it as csv file.
Remove those lines
For Each column As DataGridViewColumn In Expense.Columns
incomefile = incomefile & column.HeaderText & ","
Next
Give this a try.
Private Sub BtnExport_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnExport.Click
SFD.InitialDirectory = "C:\"
SFD.Title = "Save Your File"
SFD.Filter = "Microsoft Excel(*.xls)|*.xls|Comma Delimited File(*.csv)|*.Csv"
SFD.OverwritePrompt = True
SFD.ShowDialog()
strFileName = SFD.FileName
' If SFD.ShowDialog() = DialogResult.OK Then
If SFD.FilterIndex = 1 Then
Call export()
Else
Call csv()
End If
' End If
End Sub
Also, try it this way.
Dim numCols As DataGridViewCell
Dim sw As New System.IO.StreamWriter("d:\\output.txt")
For Each numRows As DataGridViewRow In DataGridView1.Rows
Dim intCellCount As Integer = numRows .Cells.Count
Dim intCounter As Integer = 1
For Each numCols In numRows .Cells()
If intCounter <> intCellCount Then
sw.Write(numCols .Value.ToString & ",")
Else
sw.WriteLine(numCols .Value.ToString)
End If
intCounter += 1
Next
Next

Saving ListView data with Yes / No Message Box

I have used 100% of the code presented as a solution here (and which I am extremely grateful for), but still hitting a wall. The problems is I still cant save the file with the file name I choose (see InputBox), this is because its not the same as rtb further down the code. How do I combine the two?
Code
Dim fileSaved As Boolean
Do Until fileSaved
Dim saveFile As String = InputBox("Enter a file name to save this message")
If saveFile = "" Then Exit Sub
Dim docs As String = My.Computer.FileSystem.SpecialDirectories.MyDocuments
Dim filePath As String = IO.Path.Combine(docs, "Visual Studio 2013\Projects", saveFile & ".txt")
fileSaved = True
If My.Computer.FileSystem.FileExists(filePath) Then
Dim msg As String = "File Already Exists. Do You Wish To Overwrite it?"
Dim style As MsgBoxStyle = MsgBoxStyle.YesNo Or MsgBoxStyle.DefaultButton2 Or MsgBoxStyle.Critical
fileSaved = (MsgBox(msg, style, "Warning") = MsgBoxResult.Yes)
End If
Loop
'THIS CODE save content to Test.txt NOT saveFile as desired
Dim rtb As New RichTextBox
rtb.AppendText("Generation, Num Of Juveniles, Num of Adults, Num of Semiles, Total" & vbNewLine)
For Each saveitem As ListViewItem In ListView1.Items
rtb.AppendText(
saveitem.Text & ", " &
saveitem.SubItems(1).Text & ", " &
saveitem.SubItems(2).Text & ", " &
saveitem.SubItems(3).Text & ", " &
saveitem.SubItems(4).Text & vbNewLine)
Next
rtb.SaveFile("C:\Users\RICHARD\Documents\Visual Studio 2013\Projects\Test.txt", _
RichTextBoxStreamType.PlainText)
The following code loops until a Boolean variable is set to indicate that the data was saved.
Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Dim fileSaved As Boolean
Do Until fileSaved
Dim saveFile As String = InputBox("Enter a file name to save this message")
If saveFile = "" Then Exit Sub
Dim docs As String = My.Computer.FileSystem.SpecialDirectories.MyDocuments
Dim filePath As String = IO.Path.Combine(docs, "Visual Studio 2013\Projects", saveFile & ".txt")
fileSaved = True
If My.Computer.FileSystem.FileExists(filePath) Then
Dim msg As String = "File Already Exists. Do You Wish To Overwrite it?"
Dim style As MsgBoxStyle = MsgBoxStyle.YesNo Or MsgBoxStyle.DefaultButton2 Or MsgBoxStyle.Critical
fileSaved = (MsgBox(msg, style, "Warning") = MsgBoxResult.Yes)
End If
Loop
'your code to save the data goes here
'the filePath String contains the path you want to save the file to.
End Sub
[Edit] Correct logic and created a filePath variable to store the path to the file. Also added code to allow the user to exit by entering an empty string.

VB.NET - Access to path %appdata% is denied

I was making a mod installer for a Minecraft community, when I ended with this problem:
Here's my code:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Button1.Enabled = False
Button2.Enabled = False
ComboBox1.Enabled = False
Button1.Text = "DOWNLOADING... DO NOT QUIT!"
Dim selected As String
Dim issel As Boolean
issel = False
selected = ComboBox1.SelectedItem
If selected = "Minecade Mod 1.7.2" Then
selected = "5"
issel = True
End If
If selected = "Minecade Mod 1.7.2 with OptiFine Standard" Then
selected = "3"
issel = True
End If
If selected = "Minecade Mod 1.7.2 with Optifine Ultra" Then
selected = "4"
issel = True
End If
If selected = "Minecade Mod 1.7.2 with Optifine Standard and Minecade Capes" Then
selected = "1"
issel = True
End If
If selected = "Minecade Mod 1.7.2 with Optifine Ultra and Minecade Capes" Then
selected = "2"
issel = True
End If
If issel = False Then
MsgBox("Invalid Selection! Try again.")
Else
Dim answ As Integer
answ = MsgBox("You have chosen the mod with the ID of: " & selected & "." & vbCrLf & "Do you want to install this mod?", vbYesNo)
If answ = 6 Then
If My.Computer.FileSystem.FileExists("C:\Documents and Settings\All Users\Documents\JOWD\MineCadeMod\1.7.2modded" & selected & ".zip") Then
Dim answOverW As Integer = MsgBox("The file already exists on the download location. Do you wish to download the file again (NO) or do you want to continue with the old one (YES)? (Preferred: Yes)", vbYesNo)
'6y7n
End If
'Installation process begins
Try
Dim dlPath As String = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) & "JOWD\MineCadeMod\1.7.2modded" & selected & ".zip"
My.Computer.Network.DownloadFile("http://files.casualnetwork.net/installers/moddedminec/1.7.2modded" & selected & ".zip", dlPath, "", "", False, 500, True)
Dim Unpackandinstall As Boolean = MsgBox("Download succesful. Do you want to unpack and install the archieve?", vbYesNo)
If Unpackandinstall = True Then
'UNPACK -------
'''Error occures inside the TRY tags here!'''
Try
Dim filePath As String
filePath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & ".minecraft\versions\1.7.2modded" & selected
Dim startPath As String = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) & "JOWD\MineCadeMod\1.7.2modded" & selected & ".zip"
Dim zipPath As String = filePath
Dim extractPath As String = filePath
My.Computer.FileSystem.CreateDirectory(filePath)
ZipFile.CreateFromDirectory(startPath, zipPath)
ZipFile.ExtractToDirectory(zipPath, extractPath)
MsgBox("Decompression, installation and finishing done! Ready to play!")
Catch ex As Exception
MsgBox("Error in decompression and installment proceidure." & vbCrLf & vbCrLf & ex.Message & vbCrLf & vbCrLf & "Report to JOWD, as this should NOT happen!")
Button1.Enabled = True
Button2.Enabled = True
ComboBox1.Enabled = True
Button1.Text = "Download and Install!"
End Try
'''Error area ends!'''
End If
Catch ex As Exception
Button1.Enabled = True
Button2.Enabled = True
ComboBox1.Enabled = True
Button1.Text = "Download and Install!"
MsgBox("Download failed. Error code below!" & vbCrLf & vbCrLf & ex.Message & vbCrLf & vbCrLf & "Check the main topic for a possible solution, if nothing applies leave a reply!")
Exit Sub
End Try
Else
'installation process aborted.
End If
End If
End Sub
I will be happy to answer any question related to my problem, I've tried to look help anywhere but nothing helps me!
Thanks.
Read! Edited.
Regarding the 2 answers from David Sdot and Visual Vincent, - Their answers did not fix my problem.
I tried to use the following line on the code:
filePath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & "\.minecraft\versions\1.7.2modded" & selected
Same error occurred.
Still looking for more advices from you!
Leave a comment if you want the project file to test it out.
Read! Edited.
Here's the source for the app, do your testing there!
http://files.casualnetwork.net/installers/moddedminec/source/MinecadeModInstaller_Min.zip
Ok so here's my solution to your problem:
Here, I used a WebClient instead of My.Computer.Network.DownloadFile, since I think it's better. (You use whatever you want of course)
Dim Download As New WebClient
Download.DownloadFileAsync(New Uri("http://files.casualnetwork.net/installers/moddedminec/1.7.2modded" & selected & ".zip"), dlPath)
I also noticed some stuff that had to be changed in your code.
For some reason you tried to zip your file into itself:
ZipFile.CreateFromDirectory(startPath, zipPath)
Remove this. :)
And you also tried to extract .minecraft\versions\1.7.2modded to itself by doing this:
Dim startPath As String = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) & "\JOWD\MineCadeMod\1.7.2modded" & selected & ".zip"
Dim zipPath As String = filePath
Dim extractPath As String = filePath
ZipFile.ExtractToDirectory(zipPath, extractPath)
Simply change zipPath from:
Dim zipPath As String = filePath
To:
Dim zipPath As String = startPath
Now the zipping should work fine :)
One more thing I noticed is that you couldn't skip the unzip part even if you pressed "No" in the MsBox. So I changed that code a little:
Dim Unpackandinstall As DialogResult
Unpackandinstall = MessageBox.Show("Download succesful. Do you want to unpack and install the archieve?", "", MessageBoxButtons.YesNo)
If Unpackandinstall = Windows.Forms.DialogResult.Yes Then
...
End If
Here's the whole Try block:
Try
Dim Download As New WebClient
Dim dlPath As String = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) & "\JOWD\MineCadeMod\1.7.2modded" & selected & ".zip"
Download.DownloadFileAsync(New Uri("http://files.casualnetwork.net/installers/moddedminec/1.7.2modded" & selected & ".zip"), dlPath)
Dim Unpackandinstall As DialogResult
Unpackandinstall = MessageBox.Show("Download succesful. Do you want to unpack and install the archieve?", "", MessageBoxButtons.YesNo)
If Unpackandinstall = Windows.Forms.DialogResult.Yes Then
Try
Dim filePath As String
filePath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & "\.minecraft\versions\1.7.2modded" & selected
Dim startPath As String = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) & "\JOWD\MineCadeMod\1.7.2modded" & selected & ".zip"
Dim zipPath As String = startPath
Dim extractPath As String = filePath
My.Computer.FileSystem.CreateDirectory(filePath)
'ZipFile.CreateFromDirectory(startPath, zipPath)
ZipFile.ExtractToDirectory(zipPath, extractPath)
MsgBox("Decompression, installation and finishing done! Ready to play!")
Catch ex As Exception
MsgBox("Error in decompression and installment proceidure." & vbCrLf & vbCrLf & ex.Message & vbCrLf & vbCrLf & "Report to JOWD, as this should NOT happen!")
Button1.Enabled = True
Button2.Enabled = True
ComboBox1.Enabled = True
Button1.Text = "Download and Install!"
End Try
End If
Catch ex As Exception
Button1.Enabled = True
Button2.Enabled = True
ComboBox1.Enabled = True
Button1.Text = "Download and Install!"
MsgBox("Download failed. Error code below!" & vbCrLf & vbCrLf & ex.Message & vbCrLf & vbCrLf & "Check the main topic for a possible solution, if nothing applies leave a reply!")
Exit Sub
End Try
And just replace
Download.DownloadFileAsync(New Uri("http://files.casualnetwork.net/installers/moddedminec/1.7.2modded" & selected & ".zip"), dlPath)
With your My.Computer.Network code if you'd rather use that instead. :)
Hope this helps!
filePath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & ".minecraft\versions\1.7.2modded" & selected
The path return by Environment.GetFolderPath has no \ at the end and you prepended a dot instead.
filePath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & "\minecraft\versions\1.7.2modded" & selected