代码之家  ›  专栏  ›  技术社区  ›  Nor

VB.net-如何在读取后正确关闭文本文件,以便在同一应用程序中打开进行写入

  •  0
  • Nor  · 技术社区  · 1 年前

    我有一个文本文件,我想将其读入缓冲区,然后关闭它。稍后在程序中,我想打开同一个文件进行追加。当我尝试打开它进行写入时,我遇到了一个非常熟悉的错误,即文件无法打开,因为它正被另一个进程使用。

    以下是READ代码:

    If File.Exists(outfile) Then
        '  Load existing CSV file into csvFIle string to be used a check for duplicates
        rdr = New StreamReader(outfile)
        csvFile = rdr.ReadToEnd
        rdr.Close()
        rdr.Dispose()
        rdr = Nothing '
    End If
    

    这是要打开编写的代码:

            sw = New StreamWriter(outfile, True) ' append to file
            If newFL Then   ' if the file is new then write the HEADER to the file
                If outbuff > "" Then sw.WriteLine(outbuff)
                outbuff = ""
                newFL = False
            End If
    

    必须有一种方法来完全释放文件。 任何帮助都将不胜感激。

    谢谢 也没有

    1 回复  |  直到 1 年前
        1
  •  1
  •   dbasnett    1 年前

    试图重新创建您的问题,但未能成功。

        Dim path As String = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
        path = IO.Path.Combine(path, "Test.txt")
    
        Dim line As String
        Using rdr As New IO.StreamReader(path)
            line = rdr.ReadLine
        End Using
    
        Using wrtr As New IO.StreamWriter(path, True)
            wrtr.WriteLine(line)
        End Using
    

    这让我怀疑问题出在我们没有看到的代码中。