.net 如何使用streamwriter和streamreader读写文件
我试图从.csv文件中读取内容并将其存储在变量中。稍后,我将该内容写入一个新文件。代码正在成功执行,但数据未显示在新文件中。有什么建议吗 这是我的密码:.net 如何使用streamwriter和streamreader读写文件,.net,vb.net,.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 Whi
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()
MSDN网站上有一些非常简短和非常好的教程:
我在寻找答案,因为我和你有同样的问题。
下面我和大家分享我的源代码。行得通,试试看
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()
它现在运转良好。我不知道为什么它以前不工作。很抱歉给大家带来麻烦,你能再解释一下代码在做什么以及为什么它解决了他的问题吗?当然,首先我检查txt文件是否存在,如果它不存在,我创建它。然后,如果在同一代码中有streamreader和streamwriter,则会抛出一条错误消息“另一个进程正在使用文件”。因此,关键是关闭文件并在使用它之后释放streamreader内存对象。sr.Close()sr.Dispose()之后,我们可以在相同的代码中使用它们,而不会出现任何问题。NumberOfLines中的变量值用于对txt文件中写入的行进行编号。希望对大家有用:-)VisualStudio2005退休文档