读取文本文件并将值分配给VB.Net中的变量 [英] Read a text file and assign the values to variables in VB.Net

查看:64
本文介绍了读取文本文件并将值分配给VB.Net中的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Txt文件看起来类似于:

[测试配置]

ObjectFileName = \\He2ntsd11 \pe2003 \ ObjectMapFiles \Rel6.1 \

[Datapool]

; DataPoolName = Test1

DataPoolName1 = Test2



下面的函数应该做什么:

1)逐行读取txt文件的所有内容。

2)按照上面的数据,第一行将是[测试配置] ]。如果它与[]的某些东西那么它应该跳过

3)按照上面的数据,第二行将是ObjectFileName = \\He2ntsd11 \pe2003 \ ObjectMapFiles \Rel6.1 \ 。在这种情况下,函数

应为=并将ObjectFileName拆分为一个变量并将\\He2ntsd11 \pe2003 \ObjectMapFiles \Rel6.1 \拆分为另一个变量。

4)按照上述数据,第三行将是[Datapool]。如果它与[]的某些东西那么它应该跳过

5)按照上面的数据,第四行将是; DataPoolName = Test1。如果它的某些东西以;开头然后它应该跳过

6)按照上面的数据,第五行将是DataPoolName1 = Test2。在这种情况下,函数

应为=并拆分DataPoolName1 将一个变量和Test2分成另一个变量。



Txt file looks similar to this:
[Test Configuration]
ObjectFileName=\\He2ntsd11\pe2003\ObjectMapFiles\Rel6.1\
[Datapool]
;DataPoolName=Test1
DataPoolName1=Test2

What should the below functions do:
1) Read all the contents of the txt file line by line.
2) As per above data first line will be [Test Configuration]. If its some thing with [] then it should skip
3) As per above data second line will be "ObjectFileName=\\He2ntsd11\pe2003\ObjectMapFiles\Rel6.1\".In this case the function
should read "=" and split "ObjectFileName" into one variable and "\\He2ntsd11\pe2003\ObjectMapFiles\Rel6.1\" into another variable.
4) As per above data third line will be [Datapool]. If its some thing with [] then it should skip
5) As per above data fourth line will be ";DataPoolName=Test1". If its some thing starting with ";" then it should skip
6) As per above data fifth line will be "DataPoolName1=Test2".In this case the function
should read "=" and split "DataPoolName1" into one variable and "Test2" into another variable.

Public Shared g_DatapoolName as string
Public Shared g_DatapoolName1 as string
Public Shared g_ObjectFileName as string

Public Shared Function FileToArray(ByVal sFileName As String) As Integer
	Dim strFileName As String
    Dim arrLines As New ArrayList()
    Dim objReader As System.IO.StreamReader
	Dim iRowCount As Integer = 0 ' Variable to hold the total 
    strFileName = g_iniFile_LocationName & "\" & sFileName
	If System.IO.File.Exists( strFileName ) = True Then
    ' read the file's lines into an ArrayList
        objReader = New System.IO.StreamReader(strFileName)
        Do While objReader.Peek() <> -1
            arrLines.Add(objReader.ReadLine())
			
        Loop 
		objReader.Close()
	Else
		Console.WriteLine("'" & strFileName & "' File does not exist")
	End If

	Return iRowCount

End Function
'Procedure to pass the values to variables.
Public Shared Sub LoadIniFileValuetoGlobalVariabls(sGlobalVariableName As String, sKey_Value As String)  
    'Dim Result As String
    
    Select Case sGlobalVariableName
          
           Case "g_DataPoolName"
                 g_DataPoolName = sKey_Value
           Case "g_DataPoolName1"
                 g_DataPoolName1 = sKey_Value 
           Case "g_ObjectFileName"
                 g_ObjectFileName = sKey_Value	
          
    End Select
End Sub

有人可以帮助我如何拆分读取的txt值并分配给变量。

Can someone help me how to split the read txt values and assign to variables.

推荐答案

试试这个:读/写XML文件,配置文件,INI文件或注册表 [ ^ ]

它在C#中,但大部分代码都非常明显。
Try reading this: Read/Write XML files, Config files, INI files, or the Registry[^]
It's in C#, but most of the code is pretty obvious.


你提出问题的方法有点适得其反。你展示自己所做的一切都很好。但是当你列出你认为应该实施的项目时,你正试图坚持你所关注的一些想法,但这些想法可能是好的或坏的,所以你减少了获得帮助的机会。



实际上,您需要创建一个有效的API来按键存储值。你的密钥是两级的:section - key =>值。你可以做两件事:1)创建一个复合键,section + key并将其用作字典中的键,2)用表示section的键创建一个字典,这个字典的值将是另一个带键的字典表示辅助键('='的左侧)。两种方式都有其优点,您的选择取决于典型的数据量和分布。此外,它会影响密钥的唯一性。



因此,使用类型 System.Collections.Generic而不是数组或列表。字典< key,value>

http: //msdn.microsoft.com/en-us/library/xfhwa508.aspx [ ^ ]。



逐个读取文件行。使用 StreamReader 就可以了。在阅读时,检测可以使用 string.Split(new char [] {'='}} 进行解析的类似于键=值行的部分。如果已在字典中找到该部分(在找到剖面线时对其进行测试),请向该部分添加新数据,否则首先创建一个新部分。使用新密钥执行相同操作。在每一步,检查是否已经找到一个键。



选项#1(使用复合键),您需要创建一个键类型,这将是是一个 struct 或一个,其中包含两个数据成员,一个代表段名,另一个代表=关键名称。覆盖 System.Object.Equals System.Object.GetHashCode (最简单有效的实现是:XOR哈希码为2字符串成员)。需要允许使用此类型作为字典的有效键。请参阅我过去的答案:C#.Net中的 Object.GetHashCode()方法 [ ^ ]。



-SA
Your approach to asking question is somewhat counter-productive. It's good that you show what you have done. But when you are listing your items you think you should implement, you are trying to stick to some ideas you are preoccupied with, but those ideas might be good or bad, so your reduce your chances to get help.

In fact, you need to create an effective API to store values by keys. Your keys are two-level: section — key => value. You can do two things: 1) create a compound key, section+key and use it as a key in a dictionary, 2) create a dictionary with the keys which represent section, the value of this dictionary would be another dictionary with a key representing a secondary key (left of '='). Both ways have their benefits, your choice depends on the typical volume and distribution of data. Besides, it affects the uniqueness of the key.

So, instead of array or a list, use the type System.Collections.Generic.Dictionary<key, value>:
http://msdn.microsoft.com/en-us/library/xfhwa508.aspx[^].

Read the file line by one. Using StreamReader is just fine. As you read, detect section like vs. key=value line which you can parse using string.Split(new char[] {'='}). If the section already found in the dictionary (test it as you find a section line), add new data to the section, otherwise first create a new section. Do the same with new keys. On each step, check up if a key is already found.

The option #1 (with compound key), you will need to create a key type, which would be a struct or a class with string two data members, one representing the section name, another, the "=" key name. Override System.Object.Equals and System.Object.GetHashCode (simplest and effective implementation is: XOR hash codes of two string members). It is needed to allow using this type as an effective key of the dictionary. Please see my past answer: Object.GetHashCode() Method in C#.Net[^].

—SA


Public Shared g_DatapoolName As String
   Public Shared g_DatapoolName1 As String
   Public Shared g_ObjectFileName As String

   Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

       '--- Change The Path Below To The Location Of Your Txt File
       Dim ioFile As New System.IO.StreamReader("C:\123.txt")

       Dim ioLines As String
       ioLines = ""

       '---Read All Txt File
       ioLines = ioFile.ReadToEnd

       ioFile.Close()
       ioFile.Dispose()


       '--- Split by Using The Line Feed Character
       Dim Seperate_Lines() As String = ioLines.Split(CChar(vbLf))

       '--- Determine How Many Lines Were In The Txt Document
       Dim Max As Integer = UBound(Seperate_Lines) 'Car_Transaction_TicketDataGridView.Rows.Count

       For MyCounter = 0 To Max - 1

           If Seperate_Lines(MyCounter).Contains("[") = True And Seperate_Lines(MyCounter).Contains("]") = True Then
               '---Do Nothing
               '--- Line Contains []

           ElseIf Seperate_Lines(MyCounter).Contains(";") = True Then
               '---Do Nothing
               '--- Line Contains ;

           Else
               If Seperate_Lines(MyCounter).Contains("=") = True Then
                   '--- Our Line Contains The = symbol So We'll Continue
                   Dim Parts() As String = Seperate_Lines(MyCounter).Split("=")


                   If Parts(0).Contains("ObjectFileName") = True Then
                       g_DatapoolName = Parts(1)
                   ElseIf Parts(0).Contains("DataPoolName1") = True Then
                       g_DatapoolName1 = Parts(1)
                   ElseIf Parts(0).Contains("DataPoolName") = True Then
                       g_DatapoolName = Parts(1)

                       'ElseIf Parts(0).Contains() = True Then

                   End If

               End If
           End If


       Next


   End Sub


这篇关于读取文本文件并将值分配给VB.Net中的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆