How to check whether a excel file is write protected or not in C#?
I'm developing a sample application in which I have to open an excel file and check whether the file is write protected or not. The code is
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.XlPla开发者_开发问答tform.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.
}
}
I would like know whether the file is write protected or not.
You can get the FileAttributes an like this:
if ((File.GetAttributes(fileNameAndPath) & FileAttributes.ReadOnly) > 0)
{
// The file is read-only (i.e. write-protected)
}
See for documentation: http://msdn.microsoft.com/en-us/library/system.io.fileattributes.aspx
If you want to check if the file is readonly, then you can check using File.GetAttributes()
, like this:
if(File.GetAttributes(fileNameAndPath) & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
{
//it's readonly :)
}
I think you want to look at the HasPassword
property of the WorkBook
class.
More info at: http://msdn.microsoft.com/en-us/library/microsoft.office.tools.excel.workbook.haspassword%28VS.80%29.aspx
Edit: Left my old answer below
Do you mean if the file or the workbook is readonly?
To check if the workbook is readonly the WorkBook
class has a ReadOnly
property.
Otherwise, to check the file, look at using the IO.FileInfo
class in the framework to get out the file attributes, like in the following code:
FileInfo fsi = new FileInfo("filepathandname");
if ((fsi.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly )
{
// it's readonly
}
You can check File.GetAttributes
Essentially, ReadOnly and Write-protected are the same thing. However, you might be encountering the situation where you are unable to access a file because it is being used by another process. In this case, you try to open it with a FileShare as below:
using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read,
FileShare.ReadWrite))
{
...
}
You can check protection with
activeDocument.ProtectionType
精彩评论