Link to home
Start Free TrialLog in
Avatar of Tom Knowlton
Tom KnowltonFlag for United States of America

asked on

Close file if open

I have code that opens a file.

This is what I am using:

Process.Start("C:\\Program Files\\Adobe\\Acrobat 8.0\\Acrobat\\Acrobat.exe", SavePath);

Is there a way to detect if the file is open already and close it if it is?  Even if another program has that file open?
Avatar of silemone
silemone
Flag of United States of America image

are you trying to close that process or that file?  Can you show a little more code, please.
What exactly is Process?  Anyway, I have example code for opening closing file


FileInfo objFI = new FileInfo(@"c:\myFile2.txt");
FileStream objFS = objFI.Open(FileMode.Create, FileAccess.ReadWrite);
StreamWriter objSW = new StreamWriter(objFS);
objSW.Write(strResult.ToString());
objSW.Write(strResult2.ToString());
objSW.Close();
objFS.Close();
objSW.Dispose();
objFS.Dispose();
Avatar of Tom Knowlton

ASKER

I am not sure how to distinguish between process and file.

string SavePath = "C:\\GamePlanReport_for_ID_" + def.CandidateID.ToString() + ".pdf";

def.DocumentReport.Publish(SavePath, FileFormat.PDF);

Process.Start("C:\\Program Files\\Adobe\\Acrobat 8.0\\Acrobat\\Acrobat.exe", SavePath);


I am running my code in Debug mode, which saves the PDF out to the hard drive, then proceeds to open it.

Sometimes I forget to close the file before I repeat the above process (run the debugger again).  So I get an exception that the file is in use by another process (which makes sense).

I want to programmatically close the file, then proceed with stepping through my code.
This is me just posing questions, but:

And there's No Process.Stop or Process.Close, Process.End?

Can you go  Process.Dispose() or Process = null?  and if  you did, would that leave a file open on your screen?  

use a try...catch to handles that  exception. and maybe you can  Use FileStream to Close the File.  
can you give me the API for Process...Is that a static class?
Oh..i get it...you're actually starting a real process...uhm...
ok...i understand...to close the process you're calling Process.Kill();
That's not closing the file when you end the process?
I never call Process Kill.
?  
you want the process to run forever?
ASKER CERTIFIED SOLUTION
Avatar of silemone
silemone
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial