create and write to a text file in vb.net

Posted by woolardz on Stack Overflow See other posts from Stack Overflow or by woolardz
Published on 2010-03-16T15:10:05Z Indexed on 2010/03/16 15:11 UTC
Read the original article Hit count: 244

Filed under:
|

I'm creating a small vb.net application, and I'm trying trying to write a list of results from a listview to a text file. I've looked online and found the code to open the save file dialog and write the text file. When I click save on the save file dialog, I receive an IOException with the message "The process cannot access the file 'C:\thethe.txt' because it is being used by another process." The text file is created in the correct location, but is empty. The application quits at this line "Dim fs As New FileStream(saveFileDialog1.FileName, FileMode.OpenOrCreate, FileAccess.Write)" Thanks in advance for any help.

Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
    Dim myStream As Stream
    Dim saveFileDialog1 As New SaveFileDialog()

    saveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
    saveFileDialog1.FilterIndex = 2
    saveFileDialog1.RestoreDirectory = True

    If saveFileDialog1.ShowDialog() = DialogResult.OK Then
        myStream = saveFileDialog1.OpenFile()
        If (myStream IsNot Nothing) Then
            Dim fs As New FileStream(saveFileDialog1.FileName, FileMode.OpenOrCreate, FileAccess.Write)
            Dim m_streamWriter As New StreamWriter(fs)
            m_streamWriter.Flush()
            'Write to the file using StreamWriter class
            m_streamWriter.BaseStream.Seek(0, SeekOrigin.Begin)
            'write each row of the ListView out to a tab-delimited line in a file
            For i As Integer = 0 To Me.ListView1.Items.Count - 1
                m_streamWriter.WriteLine(((ListView1.Items(i).Text & vbTab) + ListView1.Items(i).SubItems(0).ToString() & vbTab) + ListView1.Items(i).SubItems(1).ToString())
            Next
            myStream.Close()
        End If
    End If

End Sub

© Stack Overflow or respective owner

Related posts about .NET

Related posts about vb.net