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.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.
}
}
I would like know whether the file is write protected or not.
If you want to check if the file is readonly, then you can check using
File.GetAttributes()
, like this: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:
You can check protection with
You can get the FileAttributes an like this:
See for documentation: http://msdn.microsoft.com/en-us/library/system.io.fileattributes.aspx
I think you want to look at the
HasPassword
property of theWorkBook
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 aReadOnly
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:You can check File.GetAttributes