错误,因为文件已被另一个进程打开的StreamReader [英] Error opening streamreader because file is used by another process
问题描述
我开发一个应用程序来读取一个Excel US preadsheet,验证数据,然后将其映射到SQL表。这个过程是通过一个StreamReader读取该文件,验证数据,手动进行更正到Excel US preadsheet,再次验证 - 直到所有数据验证重复此过程。
I am developing an application to read an excel spreadsheet, validate the data and then map it to a sql table. The process is to read the file via a streamreader, validate the data, manually make corrections to the excel spreadsheet, validate again -- repeat this process until all data validates.
如果Excel的小号preadsheet是开放的,然后当我试图通过一个StreamReader我得到一个错误读取数据,该进程无法访问该文件...因为它正被另一个进程。有没有办法来解除锁定或以其他方式将数据读入一个StreamReader,而无需打开和关闭Excel每一次?
If the excel spreadsheet is open, then when I attempt to read the data via a streamreader I get an error, "The process cannot access the file ... because it is being used by another process." Is there a way to remove the lock or otherwise read the data into a streamreader without having to open and close excel each time?
推荐答案
当你调用 File.Open
您使用,使您可以指定超载来获取流的FileAccess
?
When you call File.Open
to get the stream are you using the overload that allows you to specify FileAccess
?
http://msdn.microsoft.com/en-us/library/ y973b725.aspx
请注意的参数:
public static FileStream Open(
string path,
FileMode mode,
FileAccess access,
FileShare share
)
您可以通过 FileAccess.Read
第三个参数,只表示你需要只读访问。您还应该设置 FileShare.Read
来让别人打开该文件为只读,而不是你自己锁定它。请注意,如果MS Excel打开与FileShare.None文件,你可能不会能够访问它。
You can pass FileAccess.Read
to the third param to indicate you only need read-only access. You should also set FileShare.Read
to allow others to open the file read-only instead of locking it yourself. Note that if MS Excel opens the file with FileShare.None, you probably wont be able to access it.
这篇关于错误,因为文件已被另一个进程打开的StreamReader的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!