文本文件到1D数组

时间:2016-05-03 10:44:59

标签: arrays vb.net text-files

感谢您抽出宝贵时间阅读此问题。我的问题是关于VB.NET并将文本文件转换为1D数组。

我的文本文件将包含30个技术公司名称。我希望从TEC读取的数据值成为名为“公司”的一维数组。然后,我希望所有公司的产品都在新的一行上输出。

请让我知道如何改进我的代码/完全纠正它。谢谢!

Dim sr As New Streamreader("Companies")
Dim words as string=""
Dim company(30) as string
Dim I as Integer=0

Do Until sr.Peek=1
Word=sr.Readline()
company(i)=word

Lstwords.Items.Add(words(i))

i=i+1

link to code as an Image

3 个答案:

答案 0 :(得分:1)

您可以使用File.ReadAllLines

来完成此操作
'Load each line of the file into an element of a string array
Dim companies() as string = System.IO.File.ReadAllLines("Companies")

For each company as string in companies
   Console.WriteLine(company)
next

答案 1 :(得分:0)

我不确定你最后的意思是"输出每一行",所以我只是在控制台中完成了它。

    Dim companies(29) As String
    Dim i As Integer = 0
    Dim sr As IO.StreamReader
    Dim filename As String
    filename = System.IO.Path.Combine(
    My.Computer.FileSystem.SpecialDirectories.MyDocuments, "companies.txt")

    If IO.File.Exists(filename) Then
        sr = IO.File.OpenText(filename)
        Do While sr.Peek <> -1
            companies(i) = sr.ReadLine
            i += 1
        Loop
        sr.Close()
    Else
        Console.WriteLine("File not found")
    End If

    For Each company As String In companies
        Console.WriteLine(company)
    Next

请注意,如果您在文本文件中没有30行公司,则此代码无法运行。修改上面的代码以处理意外情况。

答案 2 :(得分:0)

如果您想改进此代码:

Dim sr As New Streamreader("Companies")
Dim word As String = "" 'To remember the current word
Dim company(30) as string 'The list of companies
Dim i as Integer = 0 'a counter

Word = sr.Readline() 'We read the first line

While Not IsNothing(Word) 'While we read a line (See EDIT for explanation)
    Company(i) = word 'We add the word
    Lstwords.Items.Add(word) 'I suppose this is a list that you want to display
    i += 1 'Increment the counter
    Word = sr.ReadLine() 'Read the next line
End While 'End of the loop

编辑:为什么使用Not IsNothing(Word)

如果查看ReadLine() documentation,您会发现当文件结束时,该函数将返回Nothing。

因此,这是了解我们不在文件末尾的必要且充分的方法。