В настоящее время возникают проблемы с удалением / перезаписью из файла - PullRequest
0 голосов
/ 16 января 2019

В настоящее время у меня возникают проблемы при попытке удалить строку из файла и заменить эту строку другим текстом (перезаписать строку)

Код изначально начинается с извлечения содержимого файла, чтобы найти DepartmentDetails, который можно использовать, чтобы найти DepartmentBudget и вычесть AmountDue, а затем создать новый DepartmentDetails с новым бюджетом Как только это будет завершено, код добавит N̳e̳w̳ DepartmentDetails, в результате чего код с O͟l͟d͟ и N̳e̳w̳ DepartmentDetails останется в одной папке.

Код должен затем удалить O͟l͟d͟ DepartmentDetails из файла, чтобы N̳e̳w̳ DepartmentBudget занял его место. перезаписать O͟l͟d͟ DepartmentDetails новым.

Проблема в том, что код не удаляет O͟l͟d͟ DepartmentBudget, а вместо этого добавляет пробел между O͟l͟d͟ и N̳e̳w̳.

Private Sub BtnBillDept_Click(sender As Object, e As EventArgs) Handles BtnBillDept.Click
    Dim DepartmentStore As New Department
    Dim Order() As String = File.ReadAllLines(Dir$("OrderDetails.Txt"))
    Dim OrderID As String = TxtOrderID.Text
    Dim AmountDue As String = TxtAmountDue.Text
    Dim DeptID As String = (Trim(Mid(Order(OrderID), 5, 4)))
    Dim DepartmentDetails() As String = File.ReadAllLines(Dir$("DepartmentDetails.Txt"))

    Dim DepartmentBudget As String = (Trim(Mid(DepartmentDetails(DeptID), 35, 6)))

    Dim FormattedBudget As String = FormatCurrency(DepartmentBudget, 2)
    Dim YesNo As String
    Dim sw As New StreamWriter("DepartmentDetails.txt", True)

    DepartmentBudget = FormattedBudget - AmountDue
    DepartmentStore.DepartmentID = LSet(DeptID, 4)
    DepartmentStore.DepartmentHead = LSet((Trim(Mid(DepartmentDetails(DeptID), 5, 20))), 20)
    DepartmentStore.DepartmentName = LSet((Trim(Mid(DepartmentDetails(DeptID), 25, 10))), 10)
    DepartmentStore.DepartmentBudget = LSet(DepartmentBudget, 9)
    DeptID = UBound(DepartmentDetails)

    DepartmentDetails(DeptID) = ""
    File.WriteAllLines("DepartmentDetails", DepartmentDetails)
    sw.WriteLine(DepartmentStore.DepartmentID & DepartmentStore.DepartmentHead & DepartmentStore.DepartmentName & DepartmentStore.DepartmentBudget)
    sw.Close()`

    '***********************Having Problems Here***********************
    DepartmentDetails = File.ReadAllLines(Dir$("DepartmentDetails.Txt"))
    DepartmentDetails(DeptID) = ""
    File.WriteAllLines("DepartmentDetails", DepartmentDetails)
    '************************Having Problems Here**************************



    YesNo = MsgBox("Department has been billed. Would you like to delete the bill?", vbYesNo)
    If YesNo = vbYes Then

    End If


End Sub

1 Ответ

0 голосов
/ 17 января 2019

Кто решил, что этот текстовый файл будет отформатирован с полями фиксированной длины? Всего этого обрезания и дополнения можно избежать с помощью простого файла с разделителями-запятыми или XML-файла или базы данных, которой он действительно принадлежит. Код не проверен. Комментарии и объяснения в строке.

'I assume you have a class that looks something like this
'This uses automatic properties to save you having to
'type a getter, setter and backer field (the compiler adds these)
Public Class Department
    Public Property DepartmentID As Integer
    Public Property DepartmentHead As String
    Public Property DepartmentName As String
    Public Property DepartmentBudget As Decimal
End Class


Private Sub BtnBillDept_Click(sender As Object, e As EventArgs) Handles BtnBillDept.Click
    Dim DepartmentStore As New Department
    'Drag an OpenFileDialog from the ToolBox to your form
    'It will appear in the lower portion of the design window
    Dim MyFilePath As String = ""
    OpenFileDialog1.Title = "Select OrderDetails.Txt"
    If OpenFileDialog1.ShowDialog = DialogResult.OK Then
        MyFilePath = OpenFileDialog1.FileName
    End If
    Dim Order() As String = File.ReadAllLines(MyFilePath)
    'Changed data type, you use OrderID as an index for the Order array so it must be an Integer
    Dim OrderID As Integer
    'TryParse will check if you have a valid interger and fill OrderID variable
    If Not Integer.TryParse(TxtOrderID.Text, OrderID) Then
        MessageBox.Show("Please enter a valid Order ID.")
        Return
    End If
    'EDIT per comment by Codexer 
    If OrderID > Order.Length - 1 Then
        MessageBox.Show("Order Number is too high")
        Return
    End If

    Dim AmountDue As Decimal
    If Decimal.TryParse(TxtAmountDue.Text, AmountDue) Then
        MessageBox.Show("Please enter a valid Amount Due")
        Return
    End If
    'I hope you realize that the first index in Order is zero
    'Mid is an old VB6 method around for compatibility
    'Use the .net Substring (startIndex As Integer, length As Integer)
    'The indexes in the string start with zero
    Dim DeptID As Integer = CInt(Order(OrderID).Substring(5, 4).Trim) '(Trim(Mid(Order(OrderID), 5, 4)))
    OpenFileDialog1.Title = "Select DepartmentDetails.txt"
    If OpenFileDialog1.ShowDialog = DialogResult.OK Then
        MyFilePath = OpenFileDialog1.FileName
    End If
    Dim DepartmentDetails() As String = File.ReadAllLines(MyFilePath)
    Dim DepartmentBudget As Decimal = CDec(DepartmentDetails(DeptID).Substring(35, 6).Trim) '(Trim(Mid(DepartmentDetails(DeptID), 35, 6)))
    'You don't need to format anything until you want to display it
    'Dim FormattedBudget As String = FormatCurrency(DepartmentBudget, 2)
    'A MessageBox returns a DialogResult
    Dim YesNo As DialogResult
    Dim sw As New StreamWriter(MyFilePath, True)
    'Shorcut way to write DepartmentBudget - AmountDue
    DepartmentBudget -= AmountDue
    'Set the property in the class with the proper data type
    DepartmentStore.DepartmentID = DeptID
    'Then prepare a string for the writing to the fil
    Dim PaddedID = CStr(DeptID).PadLeft(4)
    'The .net replacement for LSet is .PadLeft
    DepartmentStore.DepartmentHead = DepartmentDetails(DeptID).Substring(5, 20).Trim.PadLeft(20)
    DepartmentStore.DepartmentName = DepartmentDetails(DeptID).Substring(25, 10).Trim.PadLeft(20)
    'Set the property in the class with the proper data type
    DepartmentStore.DepartmentBudget = DepartmentBudget
    'Then prepare a string for the writing to the fil
    Dim PaddedBudget = CStr(DepartmentBudget).PadLeft(9)
    sw.WriteLine(PaddedID & DepartmentStore.DepartmentHead & DepartmentStore.DepartmentName & PaddedBudget)
    sw.Close()
    '***********************Having Problems Here***********************
    'This is using the path from the most recent dialog
    DepartmentDetails = File.ReadAllLines(MyFilePath)
    'Here you are changing the value of one of the elements in the DepartmentDetails array
    DepartmentDetails(DeptID) = ""
    'Public Shared Sub WriteAllLines (path As String, contents As String())
    'The string "DepartmentDetails" is not a path
    File.WriteAllLines(MyFilePath, DepartmentDetails)
    '************************Having Problems Here**************************
    YesNo = MessageBox.Show("Department has been billed. Would you like to delete the bill?", "Delete Bill?", MessageBoxButtons.YesNo)
    If YesNo = DialogResult.Yes Then

    End If
End Sub
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...