如何使用StreamWriter和StreamReader读写文件

5

我正在尝试从一个.csv文件中读取内容并将其存储在变量中。然后我将该内容写入新文件。代码执行成功,但数据未出现在新文件中。请问有什么建议吗?

以下是我的代码:

    Dim ioFile As New System.IO.StreamReader("C:\sample.csv")

    Dim ioLine As String 
    Dim ioLines As String 
    ioLine = ioFile.ReadLine
    ioLines = ioLine
    While Not ioLine = ""
        ioLine = ioFile.ReadLine
        ioLines = ioLines & vbCrLf & ioLine

    End While
    Dim ioWriter As New System.IO.StreamWriter("C:\new.csv")
    ioWriter.WriteLine(ioLines)
    ioFile.Close()
    ioWriter.Close()

2
现在它正常工作了。我不知道为什么之前不能工作。抱歉给大家带来麻烦。 - Ram
2个回答

4

Visual Studio 2005已退役文档 - scls

1

我在寻找答案,因为我遇到了和你一样的问题。
以下是我的源代码。它可以工作,请试一试。

    If Not System.IO.File.Exists(path + "\" + fileName) Then
        System.IO.File.Create(path + "\" + fileName).Dispose()
    End If

    Dim sr As New StreamReader(path + "\" + fileName)
    Dim NumberOfLines As Integer

    Do While sr.Peek >= 0
        sr.ReadLine()
        NumberOfLines += 1
    Loop
    NumberOfLines = NumberOfLines + 1
    sr.Close()
    sr.Dispose()

    Dim sw As New System.IO.StreamWriter(file_path, False)
    sw.WriteLine(NumberOfLines.ToString().PadLeft(2, "0") + vbTab + "Your content")
    sw.Close()
    sw.Dispose()

1
你能否解释一下这段代码具体是做什么的,以及为什么它能解决他的问题? - dbmitch
1
当然,首先我会检查txt文件是否存在,如果不存在,我会创建它。然后,如果我在同一段代码中使用streamreader和streamwriter,就会抛出错误消息“文件正在被另一个进程使用”。所以,关键是在使用完之后关闭文件并释放streamreader内存对象。sr.Close() sr.Dispose()之后,我们可以在同一段代码中使用它们而不会有任何问题。NumberOfLines中的变量值用于对写入txt文件的行进行编号。希望这对你有用 :-) - TommyPozo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接