如何使用streamwriter和streamreader读取和写入文件

时间:2011-06-02 12:40:30

标签: .net vb.net

我正在尝试从.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 个答案:

答案 0 :(得分:4)

MSDN网站上有一些非常简短且非常好的教程:

  1. How to: Write text to a file
  2. How to: Read text from a file

答案 1 :(得分:1)

我正在寻找答案,因为我遇到了和U一样的问题 下面我分享你的源代码。它有效,试试吧。

    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()