2015-07-20 69 views
-4

我見過人們讀取特定行並使用split將行分割爲2個單獨的字符串。從文本文件中讀取某些值

value=0 

value=1 

因此,他們使用line.Split("="c)進行分割。

但我想知道的是如何從這樣的線讀取某個值:

"MouseColorR": 211, <-- That comma is in the file(some people seem confused) 

我怎麼能發現價值?請記住,該值可能會改變長度...

下面是代碼我有這麼遠,它不工作...

http://gyazo.com/4e5b0048f9d0e56dc94bb150c1b20618

編輯:代碼需要vb.net或C#

+0

你可能想看看https://www.nuget.org/packages/FileHelpers/ –

+0

這會不會是因爲使用'拆分一樣簡單(」 :「)'?因此分裂在結合的冒號和空間上?順便說一句,如果它是JSON,那麼你可能會發現使用內置框架方法對此進行反序列化非常容易 –

+0

@MartinParkin如何在冒號上分割然後修剪?如果該線路沒有空格發送,未來可能會保存一個問題。 –

回答

0

從字符串的結尾刪除字符,你可以使用TrimEnd()
你的字符串包含雙引號,所以你需要考慮到這些比較它與預期值時:

'set up a test string 
    Dim testString = """MouseColorR"": 211," 
    'remove the comma from the end and split into two variables from the colon 
    Dim values As String() = testString.TrimEnd(","c).Split(":"c) 
    'get the string value without the double quotes 
    Dim id As String = values(0).Trim(""""c) 
    'get the integer value 
    Dim value As Integer = CInt(values(1).Trim) 
    'show the values 
    MessageBox.Show(id & vbCrLf & value) 
0

那麼這當然不是一個特別有效的方法,但你可以手動檢查子串「MouseColorR」的存在。我會想象它是這樣工作的:

Dim strReadFile as new system.io.streamreader(filepath) 

Dim line as string 

Dim value as long 

Do while not strReadFile.endofstream 

Line = strReadFile.readline 

If line.contains ("MouseColorR") then 

Value = ctype (microsoft.visualbasic.left (line.substring (11)), (microsoft.visualbasic.len (line.substring (11))-1), long) 

Exit do 

End if 

Loop 

strReadFile.close