VB.Net System.IO.File.ReadAllText("Filename.txt") 'but then the file is in use when I try and delet

EDN Admin

Well-known member
Joined
Aug 7, 2010
Messages
12,794
Location
In the Machine
I am teaching myself VB.net and have pasted full code, and I want to delete the file called tracertAll.txt but I get an error "in use" message because I am doing a System.IO.File.ReadAllText("tracertALL.txt") but dont know how to release.
any help is greatly appreciated!
Here is the code I think is the problem:
Dim MailBody As String<br/>
MailBody = System.IO.File.ReadAllText("tracertALL.txt") set it to path of the file which you want to read.<br/>
mail.Body = MailBody

Full Code:
<pre class="prettyprint lang-vb Imports System.Net.Mail

Public Class Form1
Private Results As String
Private Delegate Sub delUpdate()
Private Finished As New delUpdate(AddressOf UpdateText)

Private Sub UpdateText()
txtResults.Text = Results
End Sub

Private Sub CMDAutomate()
Dim FileContent As String = My.Resources.mybatchfile
Dim Filename As String = "trs01all.bat"
My.Computer.FileSystem.WriteAllText(Filename, FileContent, False, System.Text.Encoding.ASCII)
Dim myprocess As New Process
Dim StartInfo As New System.Diagnostics.ProcessStartInfo
StartInfo.FileName = "trs01all.bat" starts cmd window
StartInfo.Arguments = (txtCommand.Text)
StartInfo.RedirectStandardInput = True
StartInfo.RedirectStandardOutput = True
StartInfo.UseShellExecute = False required to redirect
StartInfo.CreateNoWindow = True creates no cmd window
myprocess.StartInfo = StartInfo
myprocess.Start()
Dim SR As System.IO.StreamReader = myprocess.StandardOutput
Dim SW As System.IO.StreamWriter = myprocess.StandardInput
SW.WriteLine(txtCommand.Text) the command you wish to run.....
SW.WriteLine("exit") exits command prompt window
Results = SR.ReadToEnd returns results of the command window
SW.Close()
SR.Close()
Try
Dim SmtpServer As New SmtpClient()
Dim mail As New MailMessage()
SmtpServer.Credentials = New Net.NetworkCredential("username@email.com", "password")
SmtpServer.Port = 25
SmtpServer.Host = "smtprelay.email.com"
mail = New MailMessage()
mail.From = New MailAddress("noreply@email.com")
mail.To.Add(txtCommand.Text)
mail.Subject = "Automated Trace Route"
MailBody being set from text file.


Dim MailBody As String
MailBody = System.IO.File.ReadAllText("tracertALL.txt") set it to path of the file which you want to read.
mail.Body = MailBody


SmtpServer.Send(mail)
MsgBox("eMail sent successfully!")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
My.Computer.FileSystem.DeleteFile("trs01all.bat")
invokes Finished delegate, which updates textbox with the results text
Invoke(Finished)
End Sub

Private Sub txtResults_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtResults.TextChanged
End Sub
End Class

[/code]
<br/>
<br/>

View the full article
 
Back
Top