我正在使用 C# framework 4.5、netoffice 1.6 和 sharpdevelop 4.4.1 从 Outlook 中操作位于网络共享上的 excel 工作簿。
在某些时候,我需要将工作簿对象(ewb)的文件访问更改为读写,如下所示:
ewb.ChangeFileAccess(Excel.Enums.XlFileAccess.xlReadWrite, System.Reflection.Missing.Value, true);
在更改文件访问权限之前,我会检查文件是否在服务器上被锁定。如果文件被锁定,我将通知用户稍后重试该操作。
现在,我想在通知中包含锁定 excel 文件的用户名。我已经搜索了 msdn、netoffice 论坛等...并没有找到解决方案。我知道,如果您以读写方式打开 excel 文件,它会将用户名存储在 xlsx 文件中。如何通过 c# 访问该特定信息?
编辑:我最终这样做了:
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 "";
}
}
我们使用的是 excel 2003 和 excel 2007+ 文件格式(.xls 和 .xlsx)。对于 .xls 我必须查看 .xls 文件本身。对于 .xlsx,锁定用户存储在 ~$ temp 文件中。我知道,对于 .xls 文件,它是脏代码,但我不知道 .xls 文件格式的结构。因此,我只是读取了一堆包含 ascii 用户名的字节,然后执行一个正则表达式来提取该用户名。