Reputation: 101
In my scenario I am opening Word documents melodramatically. If the programm opens the same document it should prompt the user that the document is already opened.
Process[] pro = Process.GetProcessesByName("WINWORD");
if (pro.Length > 0)
{
foreach (Process p in pro)
{
p.kill();
}
}
I am using the above code to find the process and killing already opened documents. The problem is that it is killing word.exe so that all the other opened documents also close.
How do I find the name of the document and close that particular document only?
I used p.MainWindowTitle
to get the opened document's name but its not showing all the opened documents, rather showing the first opened document name.
What is the correct solution?
Upvotes: 1
Views: 4748
Reputation: 392954
Update
This is a general solution direction.
Use Microsoft.Office.Interop.Word:
using Microsoft.Office.Interop.Word;
class Program
{
static void Main()
{
// Open a doc file.
Application application = new Application();
Document document = application.Documents.Open("C:\\word.doc");
// Close word. if desired
// application.Quit();
}
}
I suspect word will automatically prevent opening the same document twice. If not, the Documetns interface to enumerate any currently opened documents, so you can check beforehand
Upvotes: 1
Reputation: 1631
You can use File.Open
method to open the file in non-sharing mode FileShare.None
.
FileStream stream = null;
bool isOpen = false;
try
{
stream = File.Open(@"DFilePath&Name",FileMode.Open, FileAccess.ReadWrite, FileShare.None);
}
catch(IOException)
{
isOpen = true;
//Show your prompt here.
}
finally
{
if (stream != null)
stream.Close();
}
if(!isOpen)
Process.Start(@"FilePath&Name");
If the file is already open, it will throw an IOException
which you can catch and show your prompt.
BTW why were you killing all the processes in the first place if all you had to do was to show a prompt?
Upvotes: 4