如何关闭或重新访问文本文件? [英] How do I close or re-access a Text file ?

查看:86
本文介绍了如何关闭或重新访问文本文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在读取一个文本文件并检查其内容,在这种情况下,所有行的最大长度应为16个字节.如果存在无效数据,则会重新显示我的表单,并且用户可以在重新处理文本文件之前对其进行编辑.但是,由于该文件已经打开,所以我的代码不起作用,它引发了该文件正在使用中的异常……是的,我可以确切地知道原因,但是如何处理/解决它? !?

I am reading a Text file and checking the contents, in this instance all lines should be a maximum of 16 bytes in length. If there is invalid data then my form is redisplayed and the user can edit the text file before re-processing it. However, as the file has already been opened, my code doesn''t work, it throws an exception that the file is in use ... and yes, I can see exactly why, but how do I handle / get around it ?!?

Dim myTeamCount As Int16 = 0
Dim myTextFile As New System.IO.FileStream(OpenFileDialog1.FileName, IO.FileMode.Open)
Dim myReader As New System.IO.StreamReader(myTextFile)
Dim List As New List(Of String)
Do While myReader.Peek >= 0
    If myReader.ReadLine.Length > 16 Then
        MessageBox.Show("Record Longer Than 16 Characters in This File - " & myReader.ReadLine & " - Edit & Retry.", "ERROR")
        Me.Refresh()
        Exit Do
    End If
    myTeamCount = myTeamCount + 1
    List.Add(myReader.ReadLine)
Loop



在此先感谢...



Thanks in advance ...

推荐答案

您需要先关闭文件,然后才能再次打开它,类似这样的方法应该起作用:

You need to close the file before you can open it again, something like this should work:

Dim myTeamCount As Int16 = 0
Dim myTextFile As New System.IO.FileStream(OpenFileDialog1.FileName, IO.FileMode.Open)
Dim myReader As New System.IO.StreamReader(myTextFile)
Dim List As New List(Of String)
Do While myReader.Peek >= 0
    If myReader.ReadLine.Length > 16 Then
        MessageBox.Show("Record Longer Than 16 Characters in This File - " & myReader.ReadLine & " - Edit & Retry.", "ERROR")
        myReader.Close()
        Me.Refresh()
        Exit Do
    End If
    myTeamCount = myTeamCount + 1
    List.Add(myReader.ReadLine)
Loop


这篇关于如何关闭或重新访问文本文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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