所以基本上。我必须更新文本文件中的库存水平,所以我将所有信息都放入文本文件中,如下所示:
Stock level, Target level, Restock
10, 20, 5
等我需要能够改变让我们说“10”通过将其发送到一个数组然后保存并将其发送回文本文件。例如。我拿“10”并做“10”(但作为变量) - 数量.....数量是用户订购的数量。对于这个例子,我们说Quantity = 3,那么它将“10”变为“7”并将其保存在文本文件中为“7”,所以下次打开它时会说“7”而不是“10”?任何想法都会非常感激。
答案 0 :(得分:0)
就像Plutonix所说的那样,这类东西就是为数据库制作的,你需要为每个"行"股票...但如果您绝对必须将数据存储为文本,那么将它存储为xml并将其序列化会更好。这是概念的一个例子,它只使用一个" line",但可以添加更多。它只是向您展示如何保存,重新加载,操作,然后重新保存数据:
Imports System.IO
Imports System.Xml.Serialization
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim filepath As String = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "test.xml")
Dim lstStocks As New List(Of Stock)
lstStocks.Add(New Stock("stk1", 10, 20, 5))
MsgBox(lstStocks(0).Name & vbCrLf &
"Stock Level: " & lstStocks(0).StockLevel.ToString & vbCrLf &
"Target Level: " & lstStocks(0).TargetLevel.ToString & vbCrLf &
"Restock:" & lstStocks(0).Restock.ToString)
Serialize(lstStocks, filepath)
Dim firstLoadStocks As List(Of Stock) = Deserialize(filepath)
firstLoadStocks(0).StockLevel -= 3
Serialize(firstLoadStocks, filepath)
Dim secondLoadStocks As List(Of Stock) = Deserialize(filepath)
MsgBox(secondLoadStocks(0).Name & vbCrLf &
"Stock Level: " & secondLoadStocks(0).StockLevel.ToString & vbCrLf &
"Target Level: " & secondLoadStocks(0).TargetLevel.ToString & vbCrLf &
"Restock:" & secondLoadStocks(0).Restock.ToString)
Me.Close()
End Sub
Public Sub Serialize(ByVal ListOfStocks As List(Of Stock), ByVal fp As String)
Using sw As New StreamWriter(fp)
Dim xmlSer As New XmlSerializer(ListOfStocks.GetType)
xmlSer.Serialize(sw, ListOfStocks)
End Using
End Sub
Public Function Deserialize(ByVal fp As String) As List(Of Stock)
Dim lstStocks As New List(Of Stock)
Using sr As New StreamReader(fp)
Dim xmlSer As New XmlSerializer(lstStocks.GetType)
lstStocks = xmlSer.Deserialize(sr)
End Using
Return lstStocks
End Function
End Class