如何检查一个Excel文件是写保护或不在C#中?
我正在开发一个示例应用程序,我必须打开一个excel文件,并检查文件是否被写保护。 代码是
using System.Windows.Forms; using Microsoft.Office.Core; private void button1_Click(object sender, EventArgs e) { string fileNameAndPath = @"D:\Sample\Sample1.xls"; // the above excel file is a write protected. Microsoft.Office.Interop.Excel.Application a = new Microsoft.Office.Interop.Excel.Application(); if (System.IO.File.Exists(fileNameAndPath)) { Microsoft.Office.Interop.Excel.ApplicationClass app = new Microsoft.Office.Interop.Excel.ApplicationClass(); // create the workbook object by opening the excel file. app.Workbooks.Open(fileNameAndPath,0,false,5,"","",true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t",false, true, 0,false,true,0); Microsoft.Office.Interop.Excel._Workbook w = app.Workbooks.Application.ActiveWorkbook; if (w.ReadOnly) MessageBox.Show("HI"); // the above condition is true. } }
我想知道该文件是否被写保护。
你可以像这样获得FileAttributes:
if ((File.GetAttributes(fileNameAndPath) & FileAttributes.ReadOnly) > 0) { // The file is read-only (ie write-protected) }
请参阅文档: http : //msdn.microsoft.com/en-us/library/system.io.fileattributes.aspx
如果你想检查文件是否只读,那么你可以使用File.GetAttributes()
来检查,如下所示:
if(File.GetAttributes(fileNameAndPath) & FileAttributes.ReadOnly) == FileAttributes.ReadOnly) { //it's readonly :) }
我想你想看看WorkBook
类的HasPassword
属性。
更多信息: http : //msdn.microsoft.com/en-us/library/microsoft.office.tools.excel.workbook.haspassword%28VS.80%29.aspx
编辑:下面我的旧答案
你的意思是如果文件或工作簿是只读?
要检查工作簿是否只读, WorkBook
类具有ReadOnly
属性。
否则,要检查文件,请查看使用框架中的IO.FileInfo
类来获取文件属性,如下面的代码所示:
FileInfo fsi = new FileInfo("filepathandname"); if ((fsi.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly ) { // it's readonly }
你可以检查File.GetAttributes
从本质上讲,ReadOnly和Write-protected是一回事。 但是,您可能遇到无法访问文件的情况,因为该文件正在被另一个进程使用。 在这种情况下,您尝试使用FileShare打开它,如下所示:
using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { ... }
你可以检查保护
activeDocument.ProtectionType