【发布时间】:2017-10-13 22:14:54
【问题描述】:
我使用的代码是:
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim fName As String = ""
OpenFileDialog1.InitialDirectory = "c:\desktop"
OpenFileDialog1.Filter = "CSV files (*.csv)|*.CSV"
OpenFileDialog1.FilterIndex = 2
OpenFileDialog1.RestoreDirectory = True
If (OpenFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK) Then
fName = OpenFileDialog1.FileName
End If
txtpathfile.Text = fName
Dim TextLine As String = ""
Dim SplitLine() As String
If System.IO.File.Exists(fName) = True Then
Dim objReader As New System.IO.StreamReader(fName)
Do While objReader.Peek() <> -1
TextLine = objReader.ReadLine()
SplitLine = Split(TextLine, ",")
Me.DataGridView2.Rows.Add(SplitLine)
Loop
Else
MsgBox("File Does Not Exist")
End If
End Sub
我的输出看起来编码错误:
我的代码有什么问题?请帮我。感谢您的考虑。
【问题讨论】:
-
所选文件的内容看起来像一个 zip 压缩包
-
不,先生,这不是 zip 文件。为什么我的输出类似于条形码?
-
该输出表明您正在使用错误的编码读取文件来读取文件,因此读取的字节被转换为错误的字符。创建
StreamReader时需要指定编码,例如Dim objReader As New System.IO.StreamReader(fName, Text.Encoding.ASCII)。如果您不知道使用什么编码来编写文件,那么您将不得不尝试几种不同的编码,看看哪种有效。 -
顺便说一句,当你完成文件时,你并没有关闭它。我建议使用
Using语句来创建StreamReader以确保文件已关闭,这在End Using语句中隐式发生。 -
我已经告诉过你它的用途了。如果您不理解我的解释或需要更多信息,请进行适当的研究。我们不是来教您 VB.NET 编程的基础知识。我们在这里帮助解决特定的编码问题,我已经做到了。您完全可以使用 VS 中的帮助菜单打开
StreamReader构造函数的文档并自己阅读。
标签: vb.net datagridview csv-import