views:

277

answers:

5

In a C# WinForms app, I am using System.IO.Diagnostics.Process.Start(fileName) to open files. The type of file can be .doc, .docx, .xls, .xlsx, .csv, .pdf, or .txt.

Is there any way to force these files to be opened read-only?

+5  A: 

Unfortunately, the way of doing this changes with the type of file.

The best option is to check the ProcessStartInfo.Verbs property for a known verb for your file type. This is typically "OpenAsReadOnly". You'd then set that verb, and start the process with a ProcessStartInfo.

Just realize - this doesn't work for every type of file, since it's up to the program to supply and handle an appropriate verb.

Reed Copsey
+1  A: 

Process.Start starts whatever program is associated with that file. You cannot instruct it to open the file as read-only, unless the program supports a command line argument to indicate that it should open as read-only (or if it supports the OpenAsReadOnly verb).

You could set file attributes on the file to read-only before opening it, but I don't think that is what you want.

driis
A: 

Depends on if the registered application has switch/option to support read-only mode. If so, you can pass in the read-only option. For your case, I don't think Process.Start can if no read-only option.

PerlDev
+5  A: 

You need to set the file attributes of the file before you start the process and then set them back when you opened it.

Example:

var attributes = File.GetAttributes(path);

File.SetAttributes(filePath, attributes | FileAttributes.ReadOnly);

System.IO.Diagnostics.Process.Start(fileName);

File.SetAttributes(filePath, attributes);

Note: This will change the file attributes of the actual file, so keep that in mind.

Joseph
That's actually not the same as opening the file in read-only mode in most software. Many programs (such as Word) allow you to open a file in read-only without changing the file itself. See my answer for details.
Reed Copsey
@Reed Yeah I read your answer before I added this one. I added this because of the variety of file extensions the OP indicated. I thought this would be more of a "guarantee not to mess with the file" answer.
Joseph
+1  A: 

Can you copy the file to a temporary location, and then use the temp file to launch the program?

Then you could monitor the process and upon its exit, delete the temp file?

quip