I am using C # framework 4.5, netoffice 1.6 and sharpdevelop 4.4.1 to manage an Excel workbook located on a network share from Outlook.
At some point, I need to change the access to the workbook object (ewb) file for writing as follows:
ewb.ChangeFileAccess(Excel.Enums.XlFileAccess.xlReadWrite, System.Reflection.Missing.Value, true);
Before changing access to a file, I check if the file is locked on the server. If the file is locked, I will notify the user that the action will be repeated at a later point.
Now I want to include a username that blocks the excel file in the notification. I searched msdn, netoffice forum etc. And did not find a solution. I know that if you open the excel readwrite file, it will save the username in the xlsx file. How can I access this specific piece of information through C #?
EDIT: I ended up with this:
public string GetExcelFileOwner(string path, NetOffice.ExcelApi.Enums.XlFileFormat ffmt) { string tempmark = "~$"; if(ffmt==NetOffice.ExcelApi.Enums.XlFileFormat.xlExcel8) { tempmark = ""; } string uspath = Path.Combine(Path.GetDirectoryName(path), tempmark + Path.GetFileName(path)); if (!File.Exists(uspath)) return ""; var sharing = FileShare.ReadWrite | FileShare.Delete; using (var fs = new FileStream(uspath, FileMode.Open, FileAccess.Read, sharing)) using (var br = new BinaryReader(fs, Encoding.Default)) { if(ffmt==NetOffice.ExcelApi.Enums.XlFileFormat.xlExcel8) { byte[] ByteBuffer = new byte[500]; br.BaseStream.Seek(150, SeekOrigin.Begin); br.Read(ByteBuffer, 0, 500); return matchRegex(System.Text.Encoding.UTF8.GetString(ByteBuffer), @"(?=\w\w\w)([\w, ]+)").Trim(); } else { return br.ReadString(); } } } private static string matchRegex(string txt, string rgx) { Regex r; Match m; try { r = new Regex(rgx, RegexOptions.IgnoreCase); m = r.Match(txt); if (m.Success) { return m.Groups[1].Value.ToString(); } else { return ""; } } catch { return ""; } }
We use the excel 2003 and excel 2007+ format (.xls and .xlsx). For .xls, I had to look into the .xls file. For .xlsx, the lock user is stored in the ~ $ temp file. I know that for the .xls file this is dirty code, but I do not know how the .xls file structure is structured. So I just read a bunch of bytes that includes the ascii username, and do a regex to extract that username.