编辑单独的字段时,文件将返回空白

时间:2016-05-05 04:05:46

标签: vb.net

该程序用于存储在航班上购买机票的客户的信息

Public DestinationTick As String
            Public PlaneTick As String
            Public TimeTick As String
            Public NameTick As String
            Public DayTick As String
            Public Stockitems() As String = IO.File.ReadAllLines("AM830.csv")
            Public SortedStock(Stockitems.Length - 1)
            Public Stocktypes(Stockitems.Length - 1) As Flight

    Public Structure Flight
        Public Destination As String
        Public Plane As String
        Public Time As String
        Public Name As String
        Public Day As String
        Public Address As String
    End Structure


''' when they press the button names P1A1
 System.IO.File.WriteAllText("AM830.csv", "")
        If P1A1.BackColor = Color.Red Then
            Stocktypes(0).Destination = GlobalDestination
            Stocktypes(0).Plane = GlobalPlane
            Stocktypes(0).Time = GLobalTime
            Stocktypes(0).Name = GlobalName
            Stocktypes(0).Day = GlobalDay
            Stocktypes(0).Address = GlobalAddress
            P1A1.Enabled = False
        End If


For Each item In Stocktypes
            My.Computer.FileSystem.WriteAllText("AM830.txt", item.Destination & "," & item.Plane & "," & item.Time & "," & item.Name & "," & item.Day & "," & item.Address)
        Next

此代码用于编辑具有csv格式的文本文件,该文件可以正常工作,我可以一次编辑1到所有字段。但是,当我关闭程序并再次打开它以进一步编辑文件时,它将编辑另一个字段但删除其余字段。例如:

第一次编辑

Ambuti,Plane 1,8:30,Monday,1,2
Ambuti,Plane 1,8:30,Monday,1,2
Ambuti,Plane 1,8:30,Monday,1,2
Ambuti,Plane 1,8:30,Monday,1,2
,,,,,
,,,,,
,,,,,
,,,,,
Ambuti,Plane 1,8:30,Monday,1,2
,,,,,

关闭程序并再次打开以再次编辑它 如果我要更改它显示的第五行:

,,,,,
,,,,,
,,,,,
,,,,,
Ambuti,Plane 1,8:30,Monday,1,2
,,,,,
,,,,,
,,,,,
,,,,,
,,,,,

它本应该离开其他字段并编辑第五行。

1 个答案:

答案 0 :(得分:0)

您使用的是System.IO.File.WriteAllText;

  

创建文件,将指定的字符串写入文件

这是你的问题。

您需要打开流并更新现有文件 - 这样的内容应该会有所帮助:

    using (System.IO.StreamWriter file = 
        new System.IO.StreamWriter(@"FilePath.csv", true))
    {
        file.WriteLine("New ticket information");
    }

MSDN Link for more info