在vb.net中创建并写入文本文件

时间:2010-03-16 15:10:05

标签: .net vb.net

我正在创建一个小型的vb.net应用程序,我正在尝试将列表视图中的结果列表写入文本文件。我在线查看并找到了打开保存文件对话框并编写文本文件的代码。当我在保存文件对话框中单击“保存”时,我收到一条IOException,其中显示消息“进程无法访问文件'C:\ thethe.txt',因为它正由另一个进程使用。”文本文件在正确的位置创建,但为空。应用程序退出此行“Dim fs As New FileStream(saveFileDialog1.FileName,FileMode.OpenOrCreate,FileAccess.Write)”提前感谢您的帮助。

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

3 个答案:

答案 0 :(得分:5)

您已使用SaveFileDialog.OpenFile打开了该文件的流 - 但是您尝试使用此行同时打开另一个流:

Dim fs As New FileStream(...)

为什么不使用你有的流? (或者不要拨打OpenFile。)

(顺便说一下,Using语句可以帮助您清理文件句柄,即使引发了异常。)

答案 1 :(得分:5)

尝试简化并使用StreamWriter:

    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

答案 2 :(得分:1)

您有一个未正确释放资源的正在运行的进程。也许你的调试器?

[编辑]抱歉,我误读了代码示例......