Aaron
Aaron

Reputation: 85

Delaying the use of code while a file is created?

Okay, so my program is checking to see is a textfile exist (this works) then if it doesn't exist it's creating the directory and file as well as saving the data to the file. I receive the error when it drops into the second test statement to create the text file. The program will create the directory and file, but fail to write to it. "unhandeled exception: file is being used by another process. If I click to ignore the error and run the program, I can click the save button again and it works properly.

So I guess my question is, can I somehow delay the code that writes to the file long enough for the other operation to finish, or is there a better way to structure it, so it's not an issue.

Relevant Code:

    Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click

    'create necessary directory
    'create text file
    'if file exist write to file

    If My.Computer.FileSystem.FileExists("C:\Documents and Settings\All Users\Documents\NailPolishSelector\polishColors.txt") = True Then
        MsgBox("Data Saved")

        Using sr As New IO.StreamWriter("C:\Documents and Settings\All Users\Documents\NailPolishSelector\polishColors.txt")
            For Each line In lstColors.Items
                sr.WriteLine(line)
            Next
            sr.Close()
        End Using

    ElseIf My.Computer.FileSystem.FileExists("C:\Documents and Settings\All Users\Documents\NailPolishSelector\polishColors.txt") = False Then

        My.Computer.FileSystem.CreateDirectory("C:\Documents and Settings\All Users\Documents\NailPolishSelector")
        Dim fs As FileStream = File.Create("C:\Documents and Settings\All Users\Documents\NailPolishSelector\polishColors.txt")

          'error occurs here
        Using srr As New IO.StreamWriter("C:\Documents and Settings\All Users\Documents\NailPolishSelector\polishColors.txt")
            For Each line In lstColors.Items
                srr.WriteLine(line)
            Next
            srr.Close()
        End Using

        MsgBox("File Created")
    End If


End Sub

Upvotes: 0

Views: 69

Answers (2)

Andrew Morton
Andrew Morton

Reputation: 25013

Your code can be re-written somewhat to make it simpler and more robust. I'm guessing that if the file exists then you want to replace it, but if not then please remove the 'OPTIONAL piece of code:

Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click

    ' Get the All Users documents folder
    Dim docsFolder As String = Environment.GetFolderPath(Environment.SpecialFolder.CommonDocuments)
    ' Combine it with the desired directory and filename
    Dim theFile As String = Path.Combine(docsFolder, "NailPolishSelector\polishColors.txt")

    'OPTIONAL
    ' Remove the previous version of the file
    If My.Computer.FileSystem.FileExists(theFile) Then
        File.Delete(theFile)
    End If

    ' REQUIRED: Create the directory if it doesn't exist
    If Not Directory.Exists(Path.GetDirectoryName(theFile)) Then
        Directory.CreateDirectory(Path.GetDirectoryName(theFile))
    End If

    ' Create the data file
    File.AppendAllLines(theFile, lstColors.items)

    MsgBox("Data saved.")

End Sub

(Thanks go to Magnus for pointing out File.AppendAllLines(path, lstColors.Items).)

There are a couple of things there which you may which to look up in the documentation: the use of the SpecialFolders enumeration and Path.Combine.

Upvotes: 1

DeanOC
DeanOC

Reputation: 7262

Your problem is that the file is locked by the fs FileStream object, and so the srr StreamWriter cannot write to it as it is trying to get a reference to the file by its name

So replacing

Using srr As New IO.StreamWriter("C:\Documents and Settings\All Users\Documents\NailPolishSelector\polishColors.txt")

with

Using srr As New IO.StreamWriter(fs)

should fix your problem.

Upvotes: 3

Related Questions