Is there a way to programmatically check if a Excel file is opened

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-01 12:21:40

问题


I want to check whether a particular Excel file is already opened. Otherwise when I reopen same file in my C# program it is opening in read only format. Is there any way to find out if the file is already open?


回答1:


If the file if opened by another program this code can help you figure it out, but you won't be able to open it

<!-- language: c# -->
protected virtual bool IsFileLocked(FileInfo file)
{
FileStream stream = null;

    try
    {
        stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
    }
    catch (IOException)
    {
        //the file is unavailable because it is:
        //still being written to
        //or being processed by another thread
        //or does not exist (has already been processed)
        return true;
    }
    finally
    {
        if (stream != null)
            stream.Close();
    }

    //file is not locked
    return false;
}

(BUt you can't do anything with it, the file must be closed from the program, which opened it)



来源:https://stackoverflow.com/questions/11427265/is-there-a-way-to-programmatically-check-if-a-excel-file-is-opened

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!