【问题标题】:Using the same file error使用相同的文件错误
【发布时间】:2015-07-05 20:15:53
【问题描述】:

单击按钮时,我有以下代码来编写文本框中的内容。

  Dim file As System.IO.StreamWriter
    file = My.Computer.FileSystem.OpenTextFileWriter("C:/Users/Nick/Documents/Dra.txt", False)

    file.WriteLine(NameBasic)
    file.WriteLine(LastBasic)
    file.WriteLine(PhoneBasic)
    file.WriteLine(NameEmer1)

在我的表单加载时,我从写的内容加载记事本中的内容,它说它已经被使用(文件)这是真的,我怎么能有两个不同的功能(写和读)操作同一个文件没有这个错误?

The process cannot access the file 'C:\Users\Nick\Documents\Dra.txt' because it is being used by another process.

这是我的onformload的代码

        Dim read As System.IO.StreamReader
    read = My.Computer.FileSystem.OpenTextFileReader("C:/Users/Nick/Documents/Dra.txt")
    lblNameBasic.Text = read.ReadLine

我有点卡在这个问题上,谢谢

【问题讨论】:

标签: vb.net


【解决方案1】:

完成写入后,您需要关闭文件。

 Dim file As System.IO.StreamWriter
file = My.Computer.FileSystem.OpenTextFileWriter("C:/Users/Nick/Documents/Dra.txt", False)

file.WriteLine(NameBasic)
file.WriteLine(LastBasic)
file.WriteLine(PhoneBasic)
file.WriteLine(NameEmer1)
file.Close()

【讨论】:

  • 很抱歉,我确实有,只是忘了包含它,但我忘了在 StreamReader 上添加它!
  • 那么将 read.Close() 添加到 StreamReader 是否解决了问题?
【解决方案2】:

回答你的问题:

如何让两个不同的函数(写入和读取)操作同一个文件而不会出现此错误?

如果你真的想从两个进程同时读取和写入同一个文件,你需要open the file with the FileShare.ReadWrite optionMy.Computer.FileSystem 方法不这样做。¹

但是,我怀疑您真的不想这样做。我怀疑你想,而写完之后,你想。在这种情况下,只需在使用后关闭文件就足够了。最简单的方法是使用Using 语句:

Using file = My.Computer.FileSystem.OpenTextFileWriter(...)
    file.WriteLine(...)
    file.WriteLine(...)
    ...
End Using

这确保文件将在Using 块离开后立即正确关闭(通过正常执行或通过异常)。事实上,在Using 语句中包装类实现IDisposable(例如StreamWriter)的每个 对象的使用是一种很好的做法。


¹ 根据reference sourceOpenTextFileWriter 创建了一个New IO.StreamWriter(file, append, encoding),而后者又创建了一个new FileStream(..., FileShare.Read, ...)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多