aequabit
aequabit

Reputation: 50

Create and write to file > start application > delete file in 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?

Upvotes: 0

Views: 954

Answers (3)

stormCloud
stormCloud

Reputation: 993

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

Upvotes: 2

Alex B.
Alex B.

Reputation: 2167

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.

Upvotes: 0

DAXaholic
DAXaholic

Reputation: 35358

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

Upvotes: 0

Related Questions