如何在vb.net中替换文件中的行 [英] How to replace a row in a file in vb.net

查看:74
本文介绍了如何在vb.net中替换文件中的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个csv文件,其中包含如下数据:

日期,val1,val2,val3,val4,val5,val6,....... val47,val48
18/07/2011,0,0,0,10.98,0,0,0,10.98,10.98,0,0,0,0,0 ....,0,0

现在,我需要将现有行的日期值与新行的日期值进行比较.如果相等,则需要用新行替换现有行.如果没有,请附加现有行.我尝试了以下方式.如果日期不相等,则将添加新行,但是如果日期相等,则将无法替换现有行.有什么建议吗?????

I have a csv file which have data like this:

Date,val1,val2,val3,val4,val5,val6,.......val47,val48
18/07/2011,0,0,0,10.98,0,0,0,10.98,10.98,0,0,0,0,0....,0,0

Now i need to compare the date value of existing row with new row''s date value. If equal then need to replace the existing row with new row. If not append the existing row. I tried in following way. If dates are not equal, the new row is getting added but if dates are equal could not able to replace the existing row. Any suggestions please?????

Imports System.IO
     Public Class Form1
    Private _fileName As String = "C:\Desktop\demo.csv"
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        Dim reader As New StreamReader(_fileName)
        Dim line As String = reader.ReadLine
        Dim _newLine As String = "18/07/2011,0,0,0,0,0,0,0,10.98,10.98,0,0,0,0,10.98,0,0,0,10.98"
        While line <> ""

            line = reader.ReadLine

            If line <> "" Then
                Dim values() As String = line.Split(",")

                If values(0) = "18/07/2011" Then

                    _fileName.Replace(line, _newLine)

                End If

            End If

        End While
        reader.Close()
    End Sub
End Class

推荐答案

您似乎使用字符串比较来比较日期.您应该始终使用DateTime.Equals()来比较日期,字符串比较容易出错.
这是什么代码?
You seem to use string comparison for comparing dates. You should always use DateTime.Equals() to compare dates, string comparison is prone to errors.
And what is this code?
_fileName.Replace(line, _newLine)


为什么要在filename变量中替换它,而应该在实际文件内容中替换它.


Why are you replacing it in the filename variable, you should be replacing it in the actual file content.


我可以提出的最佳建议:停止使用CSV.要多久好像XML是不够的(而且健壮得多).更好的是,使用 Data Contract 完全停止了对持久性的手动编码.请参阅 http://msdn.microsoft.com/en-us/library/ms733127.aspx [ ^ ].

—SA
Best suggestion I can make: stop using CSV. How much longer? As if XML is not enough (and much much more robust). Better yet, use Data Contract to stop this manual coding of persistence at all. See http://msdn.microsoft.com/en-us/library/ms733127.aspx[^].

—SA


这篇关于如何在vb.net中替换文件中的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆