首先,您需要了解以下几点:
- 每当一个文件被进程/线程打开时,进程/线程可以访问该文件以只读、只写或两者兼而有之。检查
FileAccess
枚举以获取更多信息。
- 此外,进程/线程可以指定对文件的访问是否是共享的(例如,只读共享、只写共享、两者都共享或根本不共享访问)。检查
FileShare
枚举以获取更多信息。
- 如果其他进程根本不共享对文件的访问权限,那么无论是用于读取还是写入,您都无法访问该文件。
现在 AFAIK,Excel 确实共享文件访问权限以进行读取,(但不共享用于写入)。因此,为了能够在 Excel 打开文件时访问该文件,您需要执行以下操作:
- 以只读方式打开文件(因为您无权写入)。
- 允许对文件进行读写访问,因为其他进程(即 Excel)需要同时具有.
问题是,虽然以只读方式File.ReadAllLines()
打开文件,但它不共享对文件的写入权限(仅用于读取)。为了澄清更多,在内部File.ReadAllLines()
使用1,它——也在内部——默认使用具有以下值的 a :2StreamReader
FileStream
New FileStream(path,
FileMode.Open,
FileAccess.Read, ' This is good.
FileShare.Read, ' This is the problem (see the code below).
' ...
除非该文件被另一个需要对该文件进行写访问的进程打开,否则该方法有效。因此,您需要为和枚举创建FileStream
并设置适当的值。因此,您的代码应如下所示:FileAccess
FileShare
Dim output As New List(Of String)
If IO.File.Exists(file) Then
Using fs As New IO.FileStream(file,
IO.FileMode.Open,
IO.FileAccess.Read, ' Open for reading only.
IO.FileShare.ReadWrite) ' Allow access for read/write.
Using reader As New IO.StreamReader(fs)
While Not reader.EndOfStream
Dim currentLine As String = reader.ReadLine()
If unique AndAlso output.Contains(currentLine) Then Continue While
output.Add(currentLine)
End While
End Using
End Using
End If
希望有帮助。
参考:
1个 InternalReadAllLines()
来源。
2 StreamReader 内部构造函数源。