从文本文件VB.net删除一行 [英] Deleting a line from a text file VB.net

查看:135
本文介绍了从文本文件VB.net删除一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我有一个上传文件的程序.文件上载后,用户输入项目编号,程序将读取文件,如果找到该项目,它将删除该项目所在的行.

我使用了以下代码

Hi

I have a program in which the files are uploaded. Once the file is uploaded a user enters a item number and the program reads the file and if the item is found it will delete the line if that item.

i have used the following code

Dim filepath As String = Me.Page.Server.MapPath("..\CSSN\" + files)
                               Dim lines As New List(Of String)(System.IO.File.ReadAllLines(filepath))

                               'Remove the line to delete, e.g.
                               lines.RemoveAt(count)

                               System.IO.File.WriteAllLines(filepath + ".old", lines.ToArray())

                           End If
                           count += 1
                           If StrReqline Is Nothing Then
                           Else
                               fields = StrReqline.ToString.Split((",").ToCharArray)
                           End If
 
Problem i am having is that a new file is created.
Is there any way in which i can delete the line without creating a new file?

                       End While

推荐答案

在实践中不行.文本文件只是字节的线性序列(除非您的代码对其进行处理,否则它们甚至不知道行").

要删除或插入任何内容,即使是该位置的整个文件中的单个字符也必须重写.尽管可以做到这一点-将文件指针放在插入/删除点,然后写入其余文件内容即可-为了安全起见,最好写入整个文件,然后重命名和/或删除原始文件.这样一来,故障将不会导致文件被更改一半.

如果您经常需要按行插入或删除项目,那么我将不使用文本文件-而是使用小型数据库,因为它们的组织方式可以有效地做到这一点.
Not in practice. Text files are just a linear sequence of bytes (they don''t even know about "lines" unless your code processes them to do so).

To delete or insert anything, even a single character the whole file from that point must be re-written. While that can be done - position the file pointer at the insert / delete point and write the rest of the file content will do it - for safety sake it is better to write the whole file, and then rename and / or delete the original. That way a failure will not cause the file to be half altered.

If you regularly need to insert or remove items on a "line" basis, then I would not use a text file - use a small database instead as they are organised to allow this efficiently.


这篇关于从文本文件VB.net删除一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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