Error opening streamreader because file is used by another process

萝らか妹 提交于 2019-11-26 22:12:33

问题


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.

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?


回答1:


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

Note the parameters:

public static FileStream Open(
    string path,
    FileMode mode,
    FileAccess access,
    FileShare share
)

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.



来源:https://stackoverflow.com/questions/2730565/error-opening-streamreader-because-file-is-used-by-another-process

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!