Restrict access to excel file opened by C# program - c#

Question 1:
I've opened an excel file with
Excel.Application app = new Excel.ApplicationClass();
Excel.Workbook Wbook = app.Workbooks.Open("aaa.xlsx",...);
Now, I want to stop other programs accessing "aaa.xlsx".
(want to restrict access by other programs like excel.exe & etc)
Are there any options that I can set to lock/block/restrict file open?
Question 2:
Since I've done this
Excel.Application app = new Excel.ApplicationClass();
I've created a new instance of excel.
I want to hide it from external use.
(I don't want it to pop up when some random excel file is double clicked on the system.)
Is there something I can do to prevent it from being called up automatically?
Any help would be much appreciated.

These should probably be separate questions, but I will try.
Also, caveat emptor: It's been a while since I've touched Office Automation and don't have the docs handy, so I'm going off memory.
The Excel.Application object should have a Visible property. Set it to false to hide the application.
As for opening the document, check the docs to see if there are any parameters like "FileAccess". I can't remember off hand, but I will keep looking...
Edit: Okay, I found the documentation on MSDN, but there doesn't appear to be any way to specify that Excel should lock the document while it's open. Sorry.

An ugly solution but you could do it:
Open and lock the file yourself. Copy it to a temporary location, load that temporary into your hidden window. After saving it copy it back to the original location. Note that both of these copies will have to be implemented in your program as the lock will preclude Windows from doing it.

Related

C# After opening an excel workbook, how can I prevent a user from opening another excel file(via windows) in the same excel instance?

I have created a program that searches excel, word, and txt files for a user entered string. So I open each file, search for the string, and add the file(with info) to a datagrid if the document contains this string.
The program works great, except for some unforseen situations. If the user did not have excel open when they start the search, the program opens a new instance of excel and begins searching. During this search, if the user then opens an excel file from windows explorer, it will open it in the same instance that my program is using, which then proceeds to show all the files it is opening, searching, then closing.
If the user already has excel open, then my program opens it's own instance and there is no issue. The exact same issue applies to word documents as well.
My question is, how can I prevent the user from opening a file in the same instance of excel that my program is currently using?
Here are the basics of how I am accessing excel:
using Excel = Microsoft.Office.Interop.Excel;
Excel.Application xlsApp = new Excel.Application();
Excel.Workbook wkb = null;
Excel.Workbooks wkbs = xlsApp.Workbooks;
xlsApp.DisplayAlerts = false;
wkb = wkbs.Open(filePath, ReadOnly: true);
//Do search here...
//Close the workbook when necessary...
wkb.Close(false);
//Close the app when necessary...
xlsApp.Quit();
I'm hoping there's some parameter I can set to prevent the user from opening documents in the same instance.
Not sure if you are still looking for a solution to this problem after all this time. I have been trying to solve this issue myself and with help from the guys at Add-In Express I have come up with a workable solution. The following should work for you.
Create your Word/Excel instance with ckNewInstance.
Open a new document/workbook
Close it.
Open the document/workbook you intend to work with.
This will normally stop any documents/workbooks being opened via your instance when the user opens via shortcut.
But sometimes this fails (eg if there are left over instances of Word in processes).
To make my instance of Word "exclusive" I am currently doing the following (until something better comes along):
Opening a dummy document as explained above.
Disable all functionality within Word which allows for opening of documents.
Just in case 1 fails try and catch any documents opened by my instance of Word and close them.
The last part of the process is kludgy, but I can't see any other way around it.
Originally, I used DocumentOpen and DocumentNew events to catch document opening and new documents and this works well. You can close the documents in these events and reopen them without apparent issue.
However, further testing showed that DocumentOpen and DocumentNew events only fire if the document is opened using your Word instance ie if the user uses the backstage for example. If they click on a Word shortcut, even though the document opens in your instance, it does not (why ever not MS?) fire the above events.
The only way I can find to capture Word documents opened by whatever means is to use the DocumentChange event and loop through each document and if it isn't the one I want, close it and reopen it.
Unfortunately, this does not work in a straightforward manner. It seems to work okay for new documents, but if the user opens an existing document and you attempt to close it in the DocumentChange event, it causes your principal document to hang (at least it does for me).
To get around this I use the DocumentChange event to find the offending docs and fire off a timer (100 ms seems to do the trick) to handle the actual closing and opening.
All in all utterly horrible and I wish someone will come back and tell me that I have wasted days on the above because Office applications have a "MakeMyInstanceUnique" property which does exactly what I need!

How update excel file that is locked by another user

Does anyone know how to handle locked excel files with c#?
I'm trying to create an application that updates an excel file that is on the network which will be probably being used by someone when someone else will try to modify it.
So far I'm not able to write and save the file when is in use, and I'm pretty new to work with Excel and C#, so any help is welcome.
Normally, when a file is locked, you cannot open it.
Excel, however, allows you to prepare a workbook to be edited by multiple persons simultaneously. You have to prepare the workbook, and certain features will become unavailable when you do so, so this won't work for just any workbook.
Also, I don't know if you can also edit the workbook in C#, although I wouldn't know why not.
The steps needed are:
On the Review tab, in the Changes group, click Share Workbook.
On the Editing tab, select the Allow changes by more than one user at the same time. This also allows workbook merging check box.
On the Advanced tab, select the options that you want to use for tracking and updating changes, and then click OK.
The full steps and an overview of general functionality and consequences of enabling this, can be found on Microsoft's website:
http://office.microsoft.com/en-us/excel-help/use-a-shared-workbook-to-collaborate-HP010096833.aspx

How to "lock" excel while interacting via COM

I have an .NET application that reads a database, does some analysis, and updates stats in an Excel spreadsheet using the COM interface. I have the application to the point where it opens the workbook (or detects it, if it's already open), and finds the sheet it needs to update.
I'm encountering an issue where the user can still interact with Excel (close the application/workbook, change data, etc.) while my application is running. I've considered hiding Excel while my app is chewing on data, but that is application-wide and prevents the user from interacting with any open spreadsheet.
Is there a way to lock Excel from changes through the COM interface, but still have it viewable/readable by the user? Alternatively, is there a way to just hide/lock a single workbook?
Application.Interactive=false;
Application.Interactive=false;
as Sid suggests is your best bet
I would suggest also changing:
Application.ScreenUpdating = false; // to avoid screen flicker
Application.DisplayAlerts = false; // if you wish to suppress most excel messages
Application.EnableEvents = false; // if there is vba in the workbook you wish to avoid triggering
Application.Calulation = xlCalculationManual; // if it's a calc intensive automation
A good idea to collect your status pre your automation and set all of these properties back to their originals when you are finished with your automation.
Would the Worksheets("Sheet1").protect( <password> ) and unprotect(<password>) do the trick?
... The only real intelligent way to do this that I can think of is to create a new instance of an Excel Application, have that one hidden and to do your changes there.
then, if the workbook is already open, just notify the user and ask them to close it.
The best way I can think of doing it is to open and them immediately hide the entire workbook. That way you can still interact with it through Interop, but the user has no visibility to it (unless they specifically unhide it but I think a lot of users don't know how to do that).
xlWorkbook.Windows[1].Visible = false;

Checking process is loaded

Is there a way to check if an application has finished loading.
For example if I were to use Process newProcess = Process.Start(#"C:\someFile.xls");
is there IsLoaded or IsFinishedLoading or something similar to that, so that another line of code does not fire until the application is fully loaded.
I ask because I get an error when trying to interface with an excel sheet because its not open. Using only Process newProcess = Process.Start(#"C:\someFile.xls"); does the job but only after my application has crashed due to no excel document being open.
Now is there a way to speed up the starting of the program/file? Or have I coded something incorrectly.
There is no generic way to know when an application started or finished opening a document.
Some programs (i.e. Office applications) provide API to communicate/control them, while others (i.e. Notepad) have no way to know this information.
Since you are already using Interop, why not actually create the Excel Application, and load the document?
You can also make the application visible to the user as well, if you need to.
using:
Excel.Application excel = new Excel.ApplicationClass();
Workbook wb = excel.Workbooks.Open(path, <parameters>);

Preventing users from using an instance of Excel

I'm using Microsoft.Office.Interop.Excel to create Excel reports with C#. Those reports have a large amount of graphics and take long time to prepare. During the preparation, The instance of the Excel application that my program uses is hidden from the user.
MY problem is that Microsoft Office tends to share application instances automatically. If the user opens an Excel workbook, Excel will try to find a running instance of Excel and open the document from there. When the user tries to open an Excel workbook while my program is running, it is attached to the instance my program uses.
This generates two problem. First, it forces my reports into visibility before they are supposed to become visible. And second, my program now needs to fight with user over the attention of the Excel instance - and my program usually loses.
So, is there any way to make the Excel instance reject requests(from the user. it should still obey to my program) to open documents, and make Office ignore my instance when it has to decide how to open an Excel document?
You could handle the Application.WorkbookOpen event. In here, either start a second instance of Excel and have it open the workbook, or close the workbook with an error message.
I also saw the Application.Interactive property. I haven't played with this, but it may be of use to you.
You can use NPOI, I suggest you visit the following link
http://npoi.codeplex.com/discussions/36157?ProjectName=npoi
I have done a little experimenting, and I think this will work:
Whenever you begin working with Excel, create two instances, and work with the second. When you're done with your work, delete the second instance and its object, then check the "UserControl" property of the first. If it returns "true", then delete only the object, but leave the process for that instance behind. If it returns "false", then delete the instance as well.
As far as I can tell, the user can open and close any number of workbooks, and it will use the first instance you created, as long as you don't delete it, and the second instance will be unmolested.

Categories

Resources