在我的应用程序中,我需要在vb.net中读取分隔文本文件
2016/05/15 21:59:13,739 [7] INFO - Login.User_Aut - o03dx1n未知 - 登录:KST028
with:
Day 2016/05/15
Time 21:59:13,739
LogType [7] INFO
MethodName Login.User_Aut
SessionID o03dx1n Unknown
LoginID Login: KST028
Message
到目前为止,这是我的代码。
OpenFileDialog1.ShowDialog()
Dim filepath As String = OpenFileDialog1.FileName
Dim inputstream As New IO.StreamReader(filepath)
Dim newstr() As String
Dim Day As String
Dim Time As String
Dim LogType As String
Dim MethodName As String
Dim SessionID As String
Dim LoginID As String
Dim Message As String
Do While inputstream.Peek <> -1
newstr = inputstream.ReadLine().Split(" ")
Day = newstr(0)
Time = newstr(1)
LogType = newstr(2)
MethodName = newstr(3)
SessionID = newstr(4)
LoginID = newstr(5)
Message = newstr(6)
Me.LogListView.Items.Add(Day)
Me.LogListView.Items.Item(LogListView.Items.Count - 1).SubItems.Add(Time)
Me.LogListView.Items.Item(LogListView.Items.Count - 1).SubItems.Add(LogType)
Me.LogListView.Items.Item(LogListView.Items.Count - 1).SubItems.Add(MethodName)
Me.LogListView.Items.Item(LogListView.Items.Count - 1).SubItems.Add(SessionID)
Me.LogListView.Items.Item(LogListView.Items.Count - 1).SubItems.Add(LoginID)
Me.LogListView.Items.Item(LogListView.Items.Count - 1).SubItems.Add(Message)
Loop
inputstream.Close()
End Sub
这段代码错了,因为: 日期和时间是正确的但是logtype,session id,loginid,列的消息是错误的
答案 0 :(得分:1)
以下是使用连字符作为分隔符来解决这个问题的方法。通过这样做,您可以收到4个部分(如果包含消息并且用连字符分隔,则为5个部分) 数组的第0个元素包含第一个连字符的所有内容,需要分解以分别使用每个部分。我已经对代码进行了评论,这些代码可以帮助您更好地理解每个部分正在做的事情。
'these would need adjusted to fit your stream
Dim inputstream As String = "2016/05/15 21:59:13,739 [7] INFO - Login.User_Aut - o03dx1n Unknown - Login: KST028"
'this produces an array of 4 elements
Dim parts() As String = inputstream.Split("-"c)
'element 0 of the array needs to be broken down into its
'proper substrings
Day = parts(0).Substring(0, 10).Trim
Time = parts(0).Substring(12, parts(0).IndexOf("[") - 12).Trim
LogType = parts(0).Substring(parts(0).IndexOf("[") - 1).Trim
'these 3 elements of the array are retrieved fromt the split on the delimiter
MethodName = parts(1).Trim
SessionID = parts(2).Trim
LoginID = parts(3).Trim
'display in console window. Here you would assign these variables to
'your listview instead.
Debug.Print(String.Format("Day={0}{7}Time={1}{7}LogType={2}{7}Method={3}{7}Session={4}{7}Login={5}{7}Message={6}", Day, Time, LogType, MethodName, SessionID, LoginID, Message, Environment.NewLine))
End Sub
同样,这并不能真正处理Message,因为你的字符串不包含一个,但是你应该能够找出如何管理它。我不确定消息是否来自字符串或稍后输入的内容