Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
355 views
in Technique[技术] by (71.8m points)

c# - Exception in opening a file that is already open

I am building an application in C# in which I have to open a CSV file to read data from it. I get an exception when I try to open the CSV file from C# when that file is already open in Excel. The exception says that the process cannot access the file since it is already open. How can I solve this problem and open the file even if it is opened in other application?

Thanks, Rakesh.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I faced this problem some time back.

You are missing the FileShare parameter. Without specifying that, if you open a file, it will be locked exclusively by your application. But since it's already been opened by Excel (or any other app), you will receive an exception.

You can try using this - I think this will be your best bet -

using (FileStream fs = File.Open(<file-path>, FileMode.Open, FileAccess.Read, FileShare.Read))

This code says: Hello Excel! If you may permit (read, not throw exception), I would like to read the file, though I will not try to own it and I know that you may modify it anytime.

If this throws error, then Excel has denied you even the read access. Too bad then! All the best.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...