如何在C#中检查Excel文件是否受写保护? [英] How to check whether a excel file is write protected or not in C#?

查看:367
本文介绍了如何在C#中检查Excel文件是否受写保护?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个示例应用程序,在该应用程序中,我必须打开一个excel文件并检查该文件是否受写保护.代码是

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.

推荐答案

您可以像这样获得FileAttributes:

You can get the FileAttributes an like this:

if ((File.GetAttributes(fileNameAndPath) & FileAttributes.ReadOnly) > 0)
{
    // The file is read-only (i.e. write-protected)
}

请参阅文档: http://msdn.microsoft .com/en-us/library/system.io.fileattributes.aspx

这篇关于如何在C#中检查Excel文件是否受写保护?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆