以只读方式打开文件

Ses*_*ame 5 c# readonly winforms

在C#WinForms应用程序中,我使用System.IO.Diagnostics.Process.Start(fileName)来打开文件.文件类型可以是.doc,.docx,.xls,.xlsx,.csv,.pdf或.txt.

有没有办法强制这些文件以只读方式打开?

Jos*_*eph 13

您需要在启动进程之前设置文件的文件属性,然后在打开它时将其设置回来.

例:

var attributes = File.GetAttributes(path);

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

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

File.SetAttributes(filePath, attributes);
Run Code Online (Sandbox Code Playgroud)

注意:这将更改实际文件的文件属性,因此请记住这一点.


Ree*_*sey 8

不幸的是,这样做的方式随文件类型而变化.

最佳选择是检查ProcessStartInfo.Verbs属性以查找文件类型的已知谓词.这通常是"OpenAsReadOnly".然后,您将设置该动词,并使用ProcessStartInfo启动该过程.

只是意识到 - 这不适用于每种类型的文件,因为它取决于程序提供和处理适当的动词.