Create and write to file > start application > delete file in VB.NET - vb.net

I'm trying to create a VB.NET application which writes multiple lines of text into a text file, then starts an application and after the application started, deletes the text file.
How exactly can I realize that?
--
Edit:
I now got this code:
Dim iniFile As String = Application.StartupPath + "\settings.ini"
If System.IO.File.Exists(iniFile) = True Then
File.Delete(iniFile)
End If
If System.IO.File.Exists(iniFile) = False Then
File.Create(iniFile)
End If
Dim fileStr As String() = {"line1", "line2", "line3"}
File.WriteAllLines(iniFile, fileStr)
Dim p As Process = Process.Start(Application.StartupPath + "\app.exe")
p.WaitForInputIdle()
If System.IO.File.Exists(iniFile) = True Then
File.Delete(iniFile)
End If
The only problem I got, is that VS is telling me, the file is in use. Between creating and editing the file. Any ideas for that?

Your code is starting the app and then moving straight on to delete the ini file.
You need to wait for the process to exit first before you continue with deleting the ini file
E.g
{code to create ini file}
'Start the process.
Dim p As Process = Process.Start(Application.StartupPath + "\app.exe")
'Wait for the process window to complete loading.
p.WaitForInputIdle()
'Wait for the process to exit.
p.WaitForExit()
{code to delete ini file}
Full example here: https://support.microsoft.com/en-us/kb/305368

Just use File.WriteAllText
Note: As others already mentioned, you should check against True in your last If
If System.IO.File.Exists(Application.StartupPath + "\settings.ini") = False Then
File.Create(Application.StartupPath + "\settings.ini")
End If
Dim fileStr As String() = {"line1", "line2", "line3"}
System.IO.File.WriteAllText(Application.StartupPath + "\settings.ini", [String].Join(Environment.NewLine, fileStr))
Process.Start(Application.StartupPath + "\app.exe")
If System.IO.File.Exists(Application.StartupPath + "\settings.ini") = True Then
File.Delete(Application.StartupPath + "\settings.ini")
End If

Use File.WriteAllLines since it
Creates a new file, write the specified string array to the file, and then closes the file. [...] If the target file already exists, it is overwritten.
msdn
Also you should use Path.Combine to setup your path
Dim path as String = Path.Combine(Application.StartupPath, "settings.ini")
Dim fileStr As String() = {"line1", "line2", "line3"}
File.WriteAllLines(path, fileStr)
Use the Path.Combine for the Process.Start and File.Delete too.

Related

VB.net: overwrite everything in a text file

in my VB.net Application id like to overwrite and add new content of a text file
What Code do I need to use?
Thanks
Read (ie: load) everything in the TXT file into your program.
Dim sFullPathToFile As String = Application.StartupPath & "\Sample.txt"
Dim sAllText As String = ""
Using xStreamReader As StreamReader = New StreamReader(sFullPathToFile)
sAllText = xStreamReader.ReadToEnd
End Using
Dim arNames As String() = Split(sAllText, vbCrLf)
'Just for fun, display the found entries in a ListBox
For iNum As Integer = 0 To UBound(arNames)
If arNames(iNum) > "" Then lstPeople.Items.Add(arNames(iNum))
Next iNum
Because you wanted to overwrite everything in the file, we now use StreamWriter (not a StreamReader like before).
'Use the True to indicate it is to be appended to existing file
'Or use False to open the file in Overwrite mode
Dim xStreamWRITER As StreamWriter = New StreamWriter(sFullPathToFile, False)
'Use the carriage return character or else each entry is on the same line
xStreamWRITER.Write("I have overwritten everything!" & vbCrLf)
xStreamWRITER.Close()

Need to open file through VB.net on another directory

Through my form, I open a .exe which is located in a folder inside debug so:
\bin\Debug\folder\ .exe
The .exe opens and creates 3 different files then closes. It is meant to create them in the same folder as the .exe but instead creates it in the Debug folder when opened through VB.net using Process.Start().
Would anyone have a possible fix for this so I don't have to move the files?
EDIT
(the .exe itself creates the files, some things may be declared outside of this sub)
Private Sub btnRunExe_Click(sender As Object, e As EventArgs) Handles btnRunExe.Click
If AcptEULA.Checked = True Then
Localpath = Application.StartupPath() + "\MCserver" + "\minecraft_server." + txtVersion.Text + ".exe"
Downloadpath = "https://s3.amazonaws.com/Minecraft.Download/versions/" + txtVersion.Text + "/minecraft_server." + txtVersion.Text + ".exe"
LocalpathParent = Application.StartupPath() + "\MCserver"
Try
Dim dirs As String() = Directory.GetFiles(LocalpathParent, "minecraft_server*.exe")
Dim dir As String
For Each dir In dirs
Process.Start(dir)
Next
Catch
'Console.WriteLine("The process failed: {0}", e.ToString())
End Try
ElseIf AcptEULA.Checked = False Then
MsgBox("You must accept the Minecraft EULA before continuing")
End If
End Sub
Process.Start could be used with a ProcessStartInfo instance in which you could set the WorkingDirectory property.
Dim psi As ProcessStartInfo = New ProcessStartInfo()
psi.WorkingDirectory = LocalpathParent
For Each fileName In Directory.EnumerateFiles(LocalpathParent, "minecraft_server*.exe")
psi.FileName = fileName
Process.Start(psi)
Next
Notice that I have changed the Directory.GetFiles with Directory.EnumerateFiles that allows you to process a file while you loop over the folder files without loading all the filenames in memory inside an array. If you still want to use GetFiles then it is
Dim psi As ProcessStartInfo = New ProcessStartInfo()
psi.WorkingDirectory = LocalpathParent
Dim files as String() = Directory.GetFiles(LocalpathParent, "minecraft_server*.exe")
For Each fileName In files
psi.FileName = fileName
Process.Start(psi)
Next
If you look at the ProcessStartInfo documentation on MSDN you could find a lot of other useful properties to fine tune how your program executes.

How to Access a txt file in a Folder created inside a VB project

I'm creating a VB project for Quiz App (in VS 2013). So I have some preset questions which are inside the project (I have created a folder inside my project and added a text file).
My question is how can I read and write contents to that file? Or if not is there any way to copy that txt file to Documents/MyAppname when installing the app so that I can edit it from that location?
In the example below I am focusing on accessing files one folder under the executable folder, not in another folder else wheres. Files are read if they exists and then depending on the first character on each line upper or lower case the line then save data back to the same file. Of course there are many ways to work with files, this is but one.
The following, created in the project folder in Solution Explorer a folder named Files, add to text files, textfile1.txt and textfile2.txt. Place several non empty lines in each with each line starting with a character. Each textfile, set in properties under solution explorer Copy to Output Directory to "Copy if newer".
Hopefully this is in tune with what you want. It may or may not work as expected via ClickOnce as I don't use ClickOnce to validate this.
In a form, one button with the following code.
Public Class Form1
Private TextFilePath As String =
IO.Path.Combine(
AppDomain.CurrentDomain.BaseDirectory, "Files")
Private TextFiles As New List(Of String) From
{
"TextFile1.txt",
"TextFile2.txt",
"TextFile3.txt"
}
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim FileName As String = ""
' loop thru each file
For Each fileBaseName As String In TextFiles
FileName = IO.Path.Combine(TextFilePath, fileBaseName)
' only access file if it exist currently
If IO.File.Exists(FileName) Then
' read file into string array
Dim contents As String() = IO.File.ReadAllLines(FileName)
' upper or lower case line based on first char.
' this means you can flip flop on each click on the button
For x As Integer = 0 To contents.Count - 1
If Char.IsUpper(CChar(contents(x))) Then
contents(x) = contents(x).ToLower
Else
contents(x) = contents(x).ToUpper
End If
Next
' save changes, being pesstimistic so we use a try-catch
Try
IO.File.WriteAllLines(FileName, contents)
Catch ex As Exception
Console.WriteLine("Attempted to save {0} failed. Error: {1}",
FileName,
ex.Message)
End Try
Else
Console.WriteLine("Does not exists {0}", FileName)
End If
Next
End Sub
End Class
This may help you
Dim objStreamReader As StreamReader
Dim strLine As String
'Pass the file path and the file name to the StreamReader constructor.
objStreamReader = New StreamReader("C:\Boot.ini")
'Read the first line of text.
strLine = objStreamReader.ReadLine
'Continue to read until you reach the end of the file.
Do While Not strLine Is Nothing
'Write the line to the Console window.
Console.WriteLine(strLine)
'Read the next line.
strLine = objStreamReader.ReadLine
Loop
'Close the file.
objStreamReader.Close()
Console.ReadLine()
You can also check this link.

Loop to print text files is skipping some files(randomly, it seems)

I have a VB.NET program which lists some text files in a directory and loops through them. For each file, the program calls notepad.exe with the /p parameter and the filename to print the file, then copies the file to a history directory, sleeps for 5 seconds(to allow notepad to open and print), and finally deletes the original file.
What's happening is, instead of printing every single text file, it is only printing "random" files from the directory. Every single text file gets copied to the history directory and deleted from the original however, so I know that it is definitely listing all of the files and attempting to process each one. I've tried adding a call to Thread.Sleep for 5000 milliseconds, then changed it to 10000 milliseconds to be sure that the original file wasn't getting deleted before notepad grabbed it to print.
I'm more curious about what is actually happening than anything (a fix would be nice too!). I manually moved some of the files that did not print to the original directory, removing them from the history directory, and reran the program, where they DID print as they should, so I know it shouldn't be the files themselves, but something to do with the code.
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim f() As String = ListFiles("l:\", "997")
Dim i As Integer
Try
For i = 0 To f.Length - 1
If Not f(i) = "" Then
System.Diagnostics.Process.Start("Notepad.exe", " /p l:\" & f(i))
My.Computer.FileSystem.CopyFile("l:\" & f(i), "k:\" & f(i))
'Thread.Sleep(5000)
Thread.Sleep(10000)
My.Computer.FileSystem.DeleteFile("l:\" & f(i))
End If
Next
'Thread.Sleep(5000)
Thread.Sleep(10000)
Catch ex As Exception
End Try
End Sub
Public Function ListFiles(ByVal strFilePath As String, ByVal strFileFilter As String) As String()
'finds all files in the strFilePath variable and matches them to the strFileFilter variable
'adds to string array strFiles if filename matches filter
Dim i As Integer = 0
Dim strFileName As String
Dim strFiles(0) As String
Dim strExclude As String = ""
Dim pos As Integer = 0
Dim posinc As Integer = 0
strFileName = Dir(strFilePath)
Do While Len(strFileName) > 0
'check to see if filename matches filter
If InStr(strFileName, strFileFilter) Then
If InStr(strFileName, "997") Then
FileOpen(1, strFilePath & strFileName, OpenMode.Input)
Do Until EOF(1)
strExclude = InputString(1, LOF(1))
Loop
pos = InStr(UCase(strExclude), "MANIFEST")
posinc = posinc + pos
pos = InStr(UCase(strExclude), "INVOICE")
posinc = posinc + pos
FileClose(1)
Else : posinc = 1
End If
If posinc > 0 Then
'add file to array
ReDim Preserve strFiles(i)
strFiles(i) = strFileName
i += 1
Else
My.Computer.FileSystem.MoveFile("l:\" & strFileName, "k:\" & strFileName)
End If
'MsgBox(strFileName & " " & IO.File.GetLastWriteTime(strFileName).ToString)
pos = 0
posinc = 0
End If
'get the next file
strFileName = Dir()
Loop
Return strFiles
End Function
Brief overview of the code above. An automated program fills the "L:\" directory with text files, and this program needs to print out certain files with "997" in the filename (namely files with "997" in the filename and containing the text "INVOICE" or "MANIFEST"). The ListFiles function does exactly this, then back in the Form1_Load() sub it is supposed to print each file, copy it, and delete the original.
Something to note, this code is developed in Visual Studio 2013 on Windows 7. The machine that actually runs this program is still on Windows XP.
I can see a few issues. the first and most obvious is the error handling:
You have a Try.. Catch with no error handling. You may be running in to an error without knowing it!! Add some output here, so you know if that is the case.
The second issue is to do with the way you are handling Process classes.
Instead of just calling System.Diagnostics.Process.Start in a loop and sleeping you should use the inbuilt method of handling execution. You are also not disposing of anything, which makes me die a little inside.
Try something like
Using p As New System.Diagnostics.Process
p.Start("Notepad.exe", " /p l:\" & f(i))
p.WaitForExit()
End Using
With both of these changes in place you should not have any issues. If you do there should at least be errors for you to look at and provide here, if necessary.

Get the output of a shell Command in VB.net

I have a VB.net program in which I call the Shell function. I would like to get the text output that is produced from this code in a file. However, this is not the return value of the executed code so I don't really know how to.
This program is a service but has access to the disk no problem as I already log other information. The whole service has multiple threads so I must also make sure that when the file is written it's not already accessed.
You won't be able to capture the output from Shell.
You will need to change this to a process and you will need to capture the the Standard Output (and possibly Error) streams from the process.
Here is an example:
Dim oProcess As New Process()
Dim oStartInfo As New ProcessStartInfo("ApplicationName.exe", "arguments")
oStartInfo.UseShellExecute = False
oStartInfo.RedirectStandardOutput = True
oProcess.StartInfo = oStartInfo
oProcess.Start()
Dim sOutput As String
Using oStreamReader As System.IO.StreamReader = oProcess.StandardOutput
sOutput = oStreamReader.ReadToEnd()
End Using
Console.WriteLine(sOutput)
To get the standard error:
'Add this next to standard output redirect
oStartInfo.RedirectStandardError = True
'Add this below
Using oStreamReader As System.IO.StreamReader = checkOut.StandardError
sOutput = oStreamReader.ReadToEnd()
End Using
Just pipe the output to a text file?
MyCommand > "c:\file.txt"
Then read the file.
Dim proc As New Process
proc.StartInfo.FileName = "C:\ipconfig.bat"
proc.StartInfo.UseShellExecute = False
proc.StartInfo.RedirectStandardOutput = True
proc.Start()
proc.WaitForExit()
Dim output() As String = proc.StandardOutput.ReadToEnd.Split(CChar(vbLf))
For Each ln As String In output
RichTextBox1.AppendText(ln & vbNewLine)
lstScan.Items.Add(ln & vbNewLine)
Next
=======================================================================
create a batch file in two lines as shown below:
echo off
ipconfig
' make sure you save this batch file as ipconfig.bat or whatever name u decide to pick but make sure u put dot bat at the end of it.