Maxter
Maxter

Reputation: 824

Open excel file in a temporary file

I have been using excel interop for a while now but decided to start using EPPLUS library instead for some reasons. I like it but I would like to open the excel files the same way Excel Interop does: Open the file as a temporary file that does not really exist anywhere. So far, EPPLUS must save the file somewhere so that I can open it using:

System.Diagnostics.Process.Start()

What I have tried so far is delete the file after I open it:

excelPack.SaveAs(new FileInfo(name));                                                          
File.SetAttributes(name, FileAttributes.ReadOnly); //Force the user to save file As                                        
System.Diagnostics.Process.Start(name);                                                                         
File.Delete(name); //Crash here. File is in use

But as you can see, it crashed at last line because the file is opened.

Upvotes: 0

Views: 865

Answers (1)

Maxter
Maxter

Reputation: 824

The Solution is quite simple. Simply set the file attributes to normal before deleting it. This will somehow tell windows that the file is no longer in use:

                excelPack.SaveAs(new FileInfo(name));                                                          
                File.SetAttributes(name, FileAttributes.ReadOnly); //Force the user to save file As                                        
                System.Diagnostics.Process.Start(name);
                File.SetAttributes(name, FileAttributes.Normal);                                                                     
                File.Delete(name); 

The file will be deleted but it will still be open in Excel in Read Only. The user will be able to save it.

Upvotes: 1

Related Questions