我正在研究VS 2012,Vb.Net-.Net 4.0框架。
我的Vb.Net代码正在读取.csv文件,预计它将在没有回车的情况下重写该文件。
但现在,Carriage Return Line Feed被创建为.csv文件中的新行。如何删除CR LF??
Public Sub Test()
Try
Dim reader As StreamReader = New System.IO.StreamReader(File.OpenRead("D:CSVTest.csv"))
Dim listA As New List(Of String)()
If File.Exists("d:CSVTestOut.csv") Then
File.Delete("d:CSVTestOut.csv")
End If
Dim sw As New StreamWriter("d:CSVTestOut.csv")
Dim s As String = String.Empty
While reader.Peek() >= 0
Dim line As String = reader.ReadLine()
Dim values As String() = line.Split(";"c)
listA.Add(values(0))
s = s + line + Chr(10)
End While
reader.Close()
sw.WriteLine(s)
sw.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
我看不出listA
或values
变量有什么好处。CRLF到LF任务不需要它们。
参见:
Try
If File.Exists("D:CSVOutput.csv") Then File.Delete("D:CSVOutput.csv")
Using reader As New StreamReader(File.OpenRead("D:CSVInput.csv"))
Using writer As New StreamWriter("D:CSVOutput.csv")
Dim strBldr As New Text.StringBuilder
While reader.Peek > -1 ' Seen like this at MSDN page for Peek() function
Dim line = reader.ReadLine
' If you really need the first value of each line, you can still do it here.
strBldr.Append(line).Append(Chr(10))
End While
writer.Write(strBldr.ToString)
End Using
End Using
Catch ex As Exception
MsgBox(ex.Message)
End Try
您应该使用流的
Using
关键字。离开时,End Using
将关闭,Dispose()
将关闭流对象。它总是会这样做,即使抛出异常或return
值;就像CCD_ 8块中的CCD_。当您像
s = s + line + Chr(10)
一样经常在末尾扩展String
-变量时,请考虑使用为此优化的StringBuilder
。当您需要列表中的第一个且仅需要第一个值时,
line.Split({";"c}, 2)
将拆分第一个值,并将其余大部分保留为一个String
,而不是数百个仅用于垃圾收集的String
对象。更合适的是使用line.Substring(0, line.IndexOf(";"))
,它根本不会产生休息。