create and write to a text file in vb.net
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 N开发者_Python百科ew 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
Try simplifying and using a StreamWriter instead:
Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
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
Using sw As New IO.StreamWriter(saveFileDialog1.FileName, False)
'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
sw.WriteLine(((ListView1.Items(i).Text & vbTab) + ListView1.Items(i).SubItems(0).ToString() & vbTab) + ListView1.Items(i).SubItems(1).ToString())
Next
End Using
End If
End Sub
You've already opened a stream to the file using SaveFileDialog.OpenFile
- but then you're trying to open another stream at the same time with this line:
Dim fs As New FileStream(...)
Why not use the stream you've got? (Or don't call OpenFile
.)
(Btw, a Using
statement would help you to clean up your file handles even if an exception is thrown.)
You have a running process that didn't released properly the resource. Maybe your debugger ?
[EDIT] Sorry, I misread the code sample...
精彩评论