简体   繁体   中英

Open file read-only

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?

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.

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.

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM