Dim NumberOfRecords As Integer
Sub Main()
Call ListTowns()
End Sub
Sub ListTowns()
Dim FileName As String
Dim MyFormat As String = "{0, -22} {1, -16} {2, -8} {3, -8}"
FileName = "Towns.csv"
Dim AllRecords As String() = System.IO.File.ReadAllLines(FileName)
Dim TownList = From record In AllRecords
Let field = record.Split(",")
Select New With {.Name = field(0), .County = field(1), .Population = field(2), .Area = field(3)}
For Each Town In TownList
Console.WriteLine(String.Format(MyFormat, Town.Name, Town.County, Town.Population, Town.Area))
Next
NumberOfRecords = TownList.Count
Console.ReadLine()
End Sub
Sub AddRecord()
Dim FileName As String
FileName = "C:\Users\Omar\Desktop\Towns.csv"
FileOpen(1, FileName, OpenMode.Random)
Dim NewRecord As String
Console.WriteLine("Enter the record you want add")
NewRecord = Console.ReadLine()
FilePut(1, NewRecord, NumberOfRecords + 1)
FileClose(1)
Console.WriteLine("The record has been added")
Console.ReadLine()
End Sub
目前程序可以列出csv文件的内容但是关于AddRecord()
Sub,当我输入数据Test,Test,Test,Test
时,它正在将该记录正确地添加到文件中并被覆盖第一张唱片。
我该如何解决这个问题?
答案 0 :(得分:0)
OpenMode.Random用于读取/写入具有固定宽度记录的文件。从你的帖子中不清楚你是否确实有固定宽度的记录(我的预感是你没有)。无论如何,要以随机模式正确读/写,你必须声明一个定义每个记录长度的结构,并告诉系统打开它时记录的长度(以便它可以移动那么多字节)到想要读/写的所需记录位置!)。按照本页标题为Random File Access中列出的链接,了解如何执行此操作。
如果你实际上没有固定宽度的记录,而是有可变长度的记录(每行一个记录,行的长度不同),那么你可以简单地将所有行存储在List(Of String)和将新记录添加到列表的末尾。现在,您只需使用System.IO.File.WriteAllLines()覆盖整个文件,类似于您对ReadAllLines()所做的操作。使用此方法,您可以修改List中的任何记录,然后只需覆盖整个文件即可更新物理文件。
以下是第二种方法的简单示例:
Module Module1
Public AllRecords As New List(Of String)
Public FileName As String = "C:\Users\Omar\Desktop\Towns.csv"
Public Sub Main()
LoadTowns()
ListTowns()
AddRecord()
ListTowns()
End Sub
Public Sub LoadTowns()
AllRecords.Clear()
AllRecords.AddRange(System.IO.File.ReadAllLines(FileName))
End Sub
Public Sub ListTowns()
Dim MyFormat As String = "{0, -22} {1, -16} {2, -8} {3, -8}"
Dim TownList = From record In AllRecords
Let field = record.Split(",")
Select New With {.Name = field(0), .County = field(1), .Population = field(2), .Area = field(3)}
For Each Town In TownList
Console.WriteLine(String.Format(MyFormat, Town.Name, Town.County, Town.Population, Town.Area))
Next
Console.ReadLine()
End Sub
Public Sub AddRecord()
Console.WriteLine("Enter the record you want add")
Dim NewRecord As String = Console.ReadLine()
AllRecords.Add(NewRecord)
System.IO.File.WriteAllLines(FileName, AllRecords.ToArray)
Console.WriteLine("The record has been added")
Console.ReadLine()
End Sub
End Module