using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Data;
using System.Data.OleDb;
using Microsoft.Win32;
using System.Runtime.InteropServices;
using Platform.Common.LogSystem;
using System.Security.Cryptography;
//add by wangfei 2012/12/14 16:00
namespace TellerSystem.Library.Ext.TradeExtension
{
///
/// 解析文件
///
public class AnalyzeFile
{
#region 变量
//文件路径
private string path;
//Excel的Sheet节点集合
private List listSheet;
//Excel按照的版本
private static string excelVerson;
//编码方式
private Encoding txt_EnCode;
//行分隔符
private char[] txt_LineSplit;
//列分隔符
private char txt_ColSplit;
private StreamReader txt_FileStream = null;
//文件流打开标志
private bool m_OpenFlag = false;
#endregion
#region 方法
///
/// 解析文本文件导入数据
///
/// 行分隔符
/// 列分割符
/// 编码方式
/// 是否显示列头
/// 返回一个DataTable
public DataTable AnalyzeTxtData(char[] txt_RowSplit, char txt_ColumnSlit, string txt_EnCode, bool isColumnHeader = true)
{
DataTable dataTabel = null;
m_OpenFlag = true;
//匹配标志
bool flag = false;
//当前行数
int rowCount = 0;
List lineData = new List();
if (txt_RowSplit == null)//分割符
{
return null;
}
if (txt_RowSplit.Length == 0)//行分割符
{
return null;
}
if (string.IsNullOrWhiteSpace(txt_ColumnSlit.ToString()))//列分割符
{
return null;
}
if (string.IsNullOrWhiteSpace(txt_EnCode))//编码方式
{
return null;
}
OpenFile(out path);
//打开文件读取流
if (!File.Exists(path))//文件不存在
{
return null;
}
this.txt_EnCode = Encoding.GetEncoding(txt_EnCode);
//行分割符字符数组,当前只支持最大两个字符的分隔符
char[] tmpStrs = txt_RowSplit;
byte[] lineByte = new byte[tmpStrs.Length];
for (int k = 0; k < tmpStrs.Length; k++)
{
lineByte[k] = Convert.ToByte(Convert.ToInt32(tmpStrs[k]));
}
this.txt_LineSplit = this.txt_EnCode.GetChars(lineByte);
//列分割符
byte[] fieldByte = new byte[1];
char[] fieldSplit = new char[1];
fieldByte[0] = Convert.ToByte(Convert.ToInt32(txt_ColumnSlit));
fieldSplit = this.txt_EnCode.GetChars(fieldByte);
this.txt_ColSplit = fieldSplit[0];
txt_FileStream = new StreamReader(path, this.txt_EnCode, true);
char temp;
StringBuilder rowData = new StringBuilder();
int readCount = 0;
//循环处理所有流数据
while (!txt_FileStream.EndOfStream)
{
//当前处理字符
temp = (char)txt_FileStream.Read();
readCount++;
//当前为第二个字符匹配时执行
if (flag)
{
//匹配不成功
if (temp != this.txt_LineSplit[1])
{
rowData.Append(this.txt_LineSplit[0]);
rowData.Append(temp);
flag = false;
//不是最后一个字符
if (!txt_FileStream.EndOfStream)
{
continue;
}
}
//匹配成功
else
{
flag = false;
}
}
else
{
//第一个字符匹配成功设置匹配成功标志
if (temp == this.txt_LineSplit[0])
{
//两个字符的情况
if (this.txt_LineSplit.Length == 2)
{
flag = true;
//不是最后一个字符
if (!txt_FileStream.EndOfStream)
{
continue;
}
else
{
rowData.Append(temp);
}
}
}
//第一个匹配不成功时按正常数据处理
else
{
rowData.Append(temp);
flag = false;
//不是最后一个字符
if (!txt_FileStream.EndOfStream)
{
if (readCount > 100000)
{
throw new Exception("找到不到指定的行分割符");
}
continue;
}
}
}
lineData.Add(rowData.ToString());
rowData.Clear();
//设置当前行数
rowCount += 1;
//行读取字符个数 清零
readCount = 0;
}
//第一行是否为字段名称
DataTable data = new DataTable("Table_Sheet1");
if (isColumnHeader)
{
//处理第一行数据位列头
lineData[0].Split(this.txt_ColSplit).ToList().ForEach
(
s =>
{
data.Columns.Add(s.Trim());
});
lineData.Remove(lineData[0]);
for (int i = 0; i < lineData.Count; i++)
{
DataRow dr = data.NewRow();
var _s = lineData[i].Split(this.txt_ColSplit);
for (int j = 0; j < _s.Count(); j++)
{
dr[j] = _s[j].ToString();
}
data.Rows.Add(dr);//在表中添加数据
}
}
else
{
//处理第一行数据位列头
for (int i = 0; i < lineData[0].Split(this.txt_ColSplit).ToList().Count; i++)
{
data.Columns.Add("col" + i);
}
for (int i = 0; i < lineData.Count; i++)
{
DataRow dr = data.NewRow();
var _s = lineData[i].Split(this.txt_ColSplit);
for (int j = 0; j < _s.Count(); j++)
{
if (j >= data.Columns.Count)
{
data.Columns.Add("col" + j);
}
dr[j] = _s[j].ToString();
}
data.Rows.Add(dr);//在表中添加数据
}
}
dataTabel = data;
return dataTabel;
}
///
/// 解析文本文件导入数据
///
/// 行分隔符
/// 列分割符
/// 编码方式
/// 是否显示列头
/// 返回一个DataTable
public List AnalyzeTxtData(bool multiSelect, char[] txt_RowSplit, char txt_ColumnSlit, string txt_EnCode, bool isColumnHeader = true)
{
List tableList = new List();
m_OpenFlag = true;
//匹配标志
bool flag = false;
//当前行数
int rowCount = 0;
List lineData = new List();
if (txt_RowSplit == null)//分割符
{
return null;
}
if (txt_RowSplit.Length == 0)//行分割符
{
return null;
}
if (string.IsNullOrWhiteSpace(txt_EnCode))//编码方式s
{
return null;
}
OpenFile(multiSelect, out path);
if (!string.IsNullOrEmpty(path))
{
StringReader reader = new StringReader(path);
string tempPath = reader.ReadLine();
while (tempPath != null)
{
if (!File.Exists(tempPath))//文件不存在
{
return null;
}
lineData.Clear();
this.txt_EnCode = Encoding.GetEncoding(txt_EnCode);
//行分割符字符数组,当前只支持最大两个字符的分隔符
char[] tmpStrs = txt_RowSplit;
byte[] lineByte = new byte[tmpStrs.Length];
for (int k = 0; k < tmpStrs.Length; k++)
{
lineByte[k] = Convert.ToByte(Convert.ToInt32(tmpStrs[k]));
}
this.txt_LineSplit = this.txt_EnCode.GetChars(lineByte);
//列分割符
byte[] fieldByte = new byte[1];
char[] fieldSplit = new char[1];
fieldByte[0] = Convert.ToByte(Convert.ToInt32(txt_ColumnSlit));
fieldSplit = this.txt_EnCode.GetChars(fieldByte);
this.txt_ColSplit = fieldSplit[0];
txt_FileStream = new StreamReader(tempPath, this.txt_EnCode, true);
char temp;
StringBuilder rowData = new StringBuilder();
int readCount = 0;
//循环处理所有流数据
while (!txt_FileStream.EndOfStream)
{
//当前处理字符
temp = (char)txt_FileStream.Read();
readCount++;
//当前为第二个字符匹配时执行
if (flag)
{
//匹配不成功
if (temp != this.txt_LineSplit[1])
{
rowData.Append(this.txt_LineSplit[0]);
rowData.Append(temp);
flag = false;
//不是最后一个字符
if (!txt_FileStream.EndOfStream)
{
continue;
}
}
//匹配成功
else
{
flag = false;
}
}
else
{
//第一个字符匹配成功设置匹配成功标志
if (temp == this.txt_LineSplit[0])
{
//两个字符的情况
if (this.txt_LineSplit.Length == 2)
{
flag = true;
//不是最后一个字符
if (!txt_FileStream.EndOfStream)
{
continue;
}
else
{
rowData.Append(temp);
}
}
}
//第一个匹配不成功时按正常数据处理
else
{
rowData.Append(temp);
flag = false;
//不是最后一个字符
if (!txt_FileStream.EndOfStream)
{
if (readCount > 100000)
{
throw new Exception("找到不到指定的行分割符");
}
continue;
}
}
}
lineData.Add(rowData.ToString());
rowData.Clear();
//设置当前行数
rowCount += 1;
//行读取字符个数 清零
readCount = 0;
}
//第一行是否为字段名称
DataTable data = new DataTable("Table_Sheet1");
if (isColumnHeader)
{
//处理第一行数据位列头
lineData[0].Split(this.txt_ColSplit).ToList().ForEach
(
s =>
{
data.Columns.Add(s.Trim());
});
lineData.Remove(lineData[0]);
for (int i = 0; i < lineData.Count; i++)
{
DataRow dr = data.NewRow();
var _s = lineData[i].Split(this.txt_ColSplit);
for (int j = 0; j < _s.Count(); j++)
{
dr[j] = _s[j].ToString();
}
data.Rows.Add(dr);//在表中添加数据
}
}
else
{
//处理第一行数据位列头
for (int i = 0; i < lineData[0].Split(this.txt_ColSplit).ToList().Count; i++)
{
data.Columns.Add("col" + i);
}
for (int i = 0; i < lineData.Count; i++)
{
DataRow dr = data.NewRow();
var _s = lineData[i].Split(this.txt_ColSplit);
for (int j = 0; j < _s.Count(); j++)
{
if (j >= data.Columns.Count)
{
data.Columns.Add("col" + j);
}
dr[j] = _s[j].ToString();
}
data.Rows.Add(dr);//在表中添加数据
}
}
data.TableName = tempPath.Substring(tempPath.LastIndexOf('\\') + 1);
tableList.Add(data);
tempPath = reader.ReadLine();
}
}
return tableList;
}
#region 代付业务解密文件的方法
private const int BUFFER_SIZE = 128 * 1024;
private const ulong FC_TAG = 0xFC010203040506CF;
///
///
///
/// 密码
///
/// 加密对象
private static SymmetricAlgorithm CreateRijndael(string password, byte[] salt)
{
PasswordDeriveBytes pdb = new PasswordDeriveBytes(password, salt, "SHA256", 1000);
SymmetricAlgorithm sma = Rijndael.Create();
sma.KeySize = 256;
sma.Key = pdb.GetBytes(32);
sma.Padding = PaddingMode.PKCS7;
return sma;
}
///
/// 检验两个Byte数组是否相同
///
/// Byte数组
/// Byte数组
/// true-相等
private static bool CheckByteArrays(byte[] b1, byte[] b2)
{
if (b1.Length == b2.Length)
{
for (int i = 0; i < b1.Length; ++i)
{
if (b1[i] != b2[i])
return false;
}
return true;
}
return false;
}
///
///
///
///
///
private DataSet EcxelToDataSet(string filePath)
{
this.CheckExcelVersion(out excelVerson);//检查Excel版本
this.GetSheets(out listSheet, filePath); //获取Excel的Sheet节点
string connString = ExcelConnString(excelVerson, filePath); //连接字符串
OleDbConnection OleConn = new OleDbConnection(connString); //连接Excel
string sql = " SELECT * FROM [" + listSheet.FirstOrDefault() + "]";
DataSet data = new DataSet();
try
{
//打开连接
OleConn.Open();
//执行查询
OleDbDataAdapter OleDaExcel = new OleDbDataAdapter(sql, OleConn);
OleDaExcel.Fill(data, "Sheet1");
//关闭连接
OleConn.Close();
}
catch (Exception ex)
{
//关闭连接
PlatformLogger.SystemErrorInfo("解析Excel文件发生异常:", ex);
OleConn.Close();
}
return data;
}
///
/// 解析加密过的Excel文件
///
///
///
public DataTable AnalyseEncryptExcelData(string password, ref string fileID)
{
DataTable dataTable = new DataTable();
this.OpenFile(out path, "Files|*.txt;"); //打开文件提示框
if (string.IsNullOrEmpty(path)) return dataTable;
//去掉前100字节的明文信息
byte[] data = File.ReadAllBytes(path);
string newfile = path.Substring(0, path.Length - 4);
//获取文件唯一ID
byte[] guidB = new byte[32];
Array.Copy(data, 100, guidB, 0, 32);
fileID = Encoding.Default.GetString(guidB);
FileStream foutN = File.OpenWrite(newfile);
foutN.Write(data, 132, data.Length - 132);
foutN.Close();
var outimp = path.Substring(0, path.LastIndexOf(".")) + ".xlsx";
using (FileStream fin = File.OpenRead(newfile), fout = File.OpenWrite(outimp))
{
int size = (int)fin.Length;
byte[] bytes = new byte[BUFFER_SIZE];
int read = -1;
int value = 0;
int outValue = 0;
byte[] IV = new byte[16];
fin.Read(IV, 0, 16);
byte[] salt = new byte[16];
fin.Read(salt, 0, 16);
SymmetricAlgorithm sma = CreateRijndael(password, salt);
sma.IV = IV;
value = 32;
long lSize = -1;
// 创建散列对象, 校验文件
HashAlgorithm hasher = SHA256.Create();
using (CryptoStream cin = new CryptoStream(fin, sma.CreateDecryptor(), CryptoStreamMode.Read),
chash = new CryptoStream(Stream.Null, hasher, CryptoStreamMode.Write))
{
// 读取文件长度
BinaryReader br = new BinaryReader(cin, Encoding.UTF8);
lSize = br.ReadInt64();
ulong tag = br.ReadUInt64();
if (FC_TAG != tag)
return dataTable;
long numReads = lSize / BUFFER_SIZE;
long slack = (long)lSize % BUFFER_SIZE;
for (int i = 0; i < numReads; ++i)
{
read = cin.Read(bytes, 0, bytes.Length);
fout.Write(bytes, 0, read);
chash.Write(bytes, 0, read);
value += read;
outValue += read;
}
if (slack > 0)
{
read = cin.Read(bytes, 0, (int)slack);
fout.Write(bytes, 0, read);
chash.Write(bytes, 0, read);
value += read;
outValue += read;
}
chash.Flush();
chash.Close();
fout.Flush();
fout.Close();
byte[] curHash = hasher.Hash;
// 获取比较和旧的散列对象
byte[] oldHash = new byte[hasher.HashSize / 8];
read = cin.Read(oldHash, 0, oldHash.Length);
if ((oldHash.Length != read) || (!CheckByteArrays(oldHash, curHash)))
return dataTable;
}
if (outValue != lSize)
return dataTable;
}
dataTable = EcxelToDataSet(outimp).Tables[0];
File.Delete(outimp);
//删除表中的所有空行,删除
if (dataTable != null)
{
bool canDel;
for (int i = 0; i < dataTable.Rows.Count; i++)
{
canDel = true;
for (int j = 0; j < dataTable.Columns.Count; j++)
{
if (dataTable.Rows[i][j].ToString().Trim() == string.Empty)
{
}
else
{
canDel = false;
dataTable.Rows[i][j] = dataTable.Rows[i][j].ToString().Replace(" ", "").Replace(" ", "");
}
}
if (canDel)
{
dataTable.Rows[i].Delete();
}
}
dataTable.AcceptChanges();
}
//删除新建文件
File.Delete(newfile);
return dataTable;
}
#endregion
///
/// 解析Excel文件导入的数据
///
/// 可选参数 RowCount=0-默认解析全部行
/// 可选参数 ColumnCount=0-默认解析全部列
/// 返回DataTable
public DataTable AnalyseExcelData(int RowCount = 0, int columnCount = 0)
{
DataTable dataTable = null;
this.OpenFile(out path, "Excel Files|*.xlsx;*.xls;"); //打开文件提示框
this.CheckExcelVersion(out excelVerson);//检查Excel版本
this.GetSheets(out listSheet); //获取Excel的Sheet节点
if (path != null && path.Trim().Length > 0)
{
string connString = ExcelConnString(excelVerson, path); //连接字符串
OleDbConnection OleConn = new OleDbConnection(connString); //连接Excel
string sql = " SELECT * FROM [" + listSheet.FirstOrDefault() + "$]";//查询字符串
DataSet data = new DataSet();
try
{
//打开连接
OleConn.Open();
//执行查询
OleDbDataAdapter OleDaExcel = new OleDbDataAdapter(sql, OleConn);
OleDaExcel.Fill(data, "Sheet1");
dataTable = data.Tables[0];
dataTable.TableName = path.Substring(path.LastIndexOf('\\') + 1);
if (RowCount > 0 && columnCount > 0)
{
DataTable dt = new DataTable(dataTable.TableName);
DataColumnCollection colums = data.Tables[0].Columns;
//处理第一行数据
for (int i = 0; i < columnCount; i++)
{
dt.Columns.Add(colums[i].ToString());
}
for (int i = 0; i < RowCount; i++)
{
DataRow dr = dt.NewRow();
for (int j = 0; j < columnCount; j++)
{
dr[j] = dataTable.Rows[i][j].ToString();
}
dt.Rows.Add(dr);//想表中添加数据
}
dataTable = null;
dataTable = dt;
}
//关闭连接
OleConn.Close();
}
catch (Exception ex)
{
//关闭连接
PlatformLogger.SystemErrorInfo("解析Excel文件发生异常:", ex);
OleConn.Close();
//写错误日志
}
}
//删除表中的所有空行
//if (dataTable != null)
//{
// bool canDel = false;
// for (int i = 0; i < dataTable.Rows.Count; i++)
// {
// for (int j = 0; j < dataTable.Columns.Count; j++)
// {
// if (dataTable.Rows[i][j].ToString() == string.Empty)
// {
// canDel = true;
// }
// else
// {
// canDel = false;
// break;
// }
// }
// if (canDel)
// {
// dataTable.Rows[i].Delete();
// }
// }
// dataTable.AcceptChanges();
//}
//删除表中的所有空行,删除
if (dataTable != null)
{
bool canDel;
for (int i = 0; i < dataTable.Rows.Count; i++)
{
canDel = true;
for (int j = 0; j < dataTable.Columns.Count; j++)
{
if (dataTable.Rows[i][j].ToString().Trim() == string.Empty)
{
}
else
{
canDel = false;
dataTable.Rows[i][j] = dataTable.Rows[i][j].ToString().Replace(" ", "").Replace(" ", "");
}
}
if (canDel)
{
dataTable.Rows[i].Delete();
}
}
dataTable.AcceptChanges();
}
return dataTable;
}
#endregion
#region 私有方法
///
/// 取得Excel文件的所有信息
///
/// 返回所有Sheet信息
private void GetSheets(out List outSheets)
{
//连接字符串
string connString = ExcelConnString(excelVerson, path);
DataTable tableInfo;
List oList = new List();
string tmpstr = "";
try
{
OleDbConnection objConn = new OleDbConnection(connString);
//打开连接
objConn.Open();
tableInfo = objConn.GetSchema("TABLES");
//处理所有SHEET信息
for (int i = 0; i < tableInfo.Rows.Count; i++)
{
tmpstr = tableInfo.Rows[i]["TABLE_NAME"].ToString();
if (tmpstr.LastIndexOf('$') == tmpstr.Length - 1)
{
oList.Add(tmpstr.Trim().TrimEnd('$'));
}
}
//关闭连接
objConn.Close();
}
catch (Exception ex)
{
PlatformLogger.SystemErrorInfo("解析Excel文件发生异常:", ex);
//写错误日志
}
//返回值
outSheets = oList;
}
///
/// 取得Excel文件的所有信息
///
/// 返回所有Sheet信息
private void GetSheets(out List outSheets, string path)
{
//连接字符串
string connString = ExcelConnString(excelVerson, path);
DataTable tableInfo;
List oList = new List();
string tmpstr = "";
try
{
OleDbConnection objConn = new OleDbConnection(connString);
//打开连接
objConn.Open();
tableInfo = objConn.GetSchema("TABLES");
//处理所有SHEET信息
for (int i = 0; i < tableInfo.Rows.Count; i++)
{
tmpstr = tableInfo.Rows[i]["TABLE_NAME"].ToString();
//这种判断方式是错误的,因为sheet页标签的名字很可能是全数字,解析的结果就是数字+$+’
//if (tmpstr.LastIndexOf('$') == tmpstr.Length - 1)
//{
// oList.Add(tmpstr.Trim().TrimEnd('$'));
//}
oList.Add(tmpstr);
}
//关闭连接
objConn.Close();
}
catch (Exception ex)
{
PlatformLogger.SystemErrorInfo("解析Excel文件发生异常:", ex);
//写错误日志
}
//返回值
outSheets = oList;
}
///
/// 检查本地Excel版本
///
/// Excel版本号
private string CheckExcelVersion(out string ExcelVersion)
{
ExcelVersion = string.Empty;
string path03 = string.Empty;
string path07 = string.Empty;
string path10 = string.Empty;
string path13 = string.Empty;
if (Environment.Is64BitOperatingSystem) //64位系统
{
path03 = Get64BitRegistryKey(@"SOFTWARE\\Microsoft\\Office\\11.0\\Excel\\InstallRoot\\", "Path");
if (string.IsNullOrEmpty(path03)) //如果未取到,可能是64系统装的32位office,需取32位注册表
{
path03 = Get32BitRegistryKey(@"SOFTWARE\\Microsoft\\Office\\11.0\\Excel\\InstallRoot\\", "Path");
}
path07 = Get64BitRegistryKey(@"SOFTWARE\\Microsoft\\Office\\12.0\\Excel\\InstallRoot\\", "Path");
if (string.IsNullOrEmpty(path07))//如果未取到,可能是64系统装的32位office,需取32位注册表
{
path07 = Get32BitRegistryKey(@"SOFTWARE\\Microsoft\\Office\\12.0\\Excel\\InstallRoot\\", "Path");
}
path10 = Get64BitRegistryKey(@"SOFTWARE\\Microsoft\\Office\\14.0\\Excel\\InstallRoot\\", "Path");
if (string.IsNullOrEmpty(path10))//如果未取到,可能是64系统装的32位office,需取32位注册表
{
path10 = Get32BitRegistryKey(@"SOFTWARE\\Microsoft\\Office\\14.0\\Excel\\InstallRoot\\", "Path");
}
path13 = Get64BitRegistryKey(@"SOFTWARE\\Microsoft\\Office\\15.0\\Excel\\InstallRoot\\", "Path");
if (string.IsNullOrEmpty(path13))//如果未取到,可能是64系统装的32位office,需取32位注册表
{
path13 = Get32BitRegistryKey(@"SOFTWARE\\Microsoft\\Office\\15.0\\Excel\\InstallRoot\\", "Path");
}
}
else //32位系统
{
path03 = Get32BitRegistryKey(@"SOFTWARE\\Microsoft\\Office\\11.0\\Excel\\InstallRoot\\", "Path");
path07 = Get32BitRegistryKey(@"SOFTWARE\\Microsoft\\Office\\12.0\\Excel\\InstallRoot\\", "Path");
path10 = Get32BitRegistryKey(@"SOFTWARE\\Microsoft\\Office\\14.0\\Excel\\InstallRoot\\", "Path");
path13 = Get32BitRegistryKey(@"SOFTWARE\\Microsoft\\Office\\15.0\\Excel\\InstallRoot\\", "Path");
}
//检查本机是否安装Office2003
if (File.Exists(path03 + "EXCEL.exe"))
{
ExcelVersion = "8.0";
}
//检查本机是否安装Office2007
if (File.Exists(path07 + "EXCEL.exe"))
{
ExcelVersion = "12.0";
}
//检查本机是否安装Office2010
if (File.Exists(path10 + "EXCEL.exe"))
{
ExcelVersion = "12.0";
}
//检查本机是否安装Office2013
if (File.Exists(path13 + "EXCEL.exe"))
{
ExcelVersion = "12.0";
}
//如果在注册表中找不到安装目录,设置初始值
if (string.IsNullOrEmpty(ExcelVersion))
{
ExcelVersion = "12.0";
}
return ExcelVersion;
}
#region 32位程序读取64位系统注册表(HKEY_LOCAL_MACHINE目录)
// 关闭64位(文件系统)的操作转向
[DllImport("Kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern bool Wow64DisableWow64FsRedirection(ref IntPtr ptr);
// 开启64位(文件系统)的操作转向
[DllImport("Kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern bool Wow64RevertWow64FsRedirection(IntPtr ptr);
// 获取操作Key值句柄
[DllImport("Advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern uint RegOpenKeyEx(UIntPtr hKey, string lpSubKey, uint ulOptions,
int samDesired, out IntPtr phkResult);
//关闭注册表转向(禁用特定项的注册表反射)
[DllImport("Advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern long RegDisableReflectionKey(IntPtr hKey);
//使能注册表转向(开启特定项的注册表反射)
[DllImport("Advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern long RegEnableReflectionKey(IntPtr hKey);
//获取Key值(即:Key值句柄所标志的Key对象的值)
[DllImport("Advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern int RegQueryValueEx(IntPtr hKey, string lpValueName, int lpReserved,
out uint lpType, System.Text.StringBuilder lpData,
ref uint lpcbData);
private string Get64BitRegistryKey(string subKeyName, string keyName)
{
int KEY_QUERY_VALUE = (0x0001);
int KEY_WOW64_64KEY = (0x0100);
int KEY_ALL_WOW64 = (KEY_QUERY_VALUE | KEY_WOW64_64KEY);
try
{
//将Windows注册表主键名转化成为不带正负号的整形句柄(与平台是32或者64位有关)
UIntPtr hKey = (UIntPtr)0x80000002;
//声明将要获取Key值的句柄
IntPtr pHKey = IntPtr.Zero;
//记录读取到的Key值
StringBuilder result = new StringBuilder(1024);
uint resultSize = 1024;
uint lpType = 0;
//关闭文件系统转向
IntPtr oldWOW64State = new IntPtr();
if (Wow64DisableWow64FsRedirection(ref oldWOW64State))
{
//获得操作Key值的句柄
RegOpenKeyEx(hKey, subKeyName, 0, KEY_ALL_WOW64, out pHKey);
//关闭注册表转向(禁止特定项的注册表反射)
RegDisableReflectionKey(pHKey);
//获取访问的Key值
RegQueryValueEx(pHKey, keyName, 0, out lpType, result, ref resultSize);
//打开注册表转向(开启特定项的注册表反射)
RegEnableReflectionKey(pHKey);
}
//打开文件系统转向
Wow64RevertWow64FsRedirection(oldWOW64State);
//返回Key值
return result.ToString().Trim();
}
catch (Exception ex)
{
//写错误日志
PlatformLogger.SystemErrorInfo("解析Excel文件发生异常:", ex);
return string.Empty;
}
}
#endregion
#region 32位程序读取32位系统注册表(HKEY_LOCAL_MACHINE目录)
private string Get32BitRegistryKey(string subKeyName, string keyName)
{
string result = string.Empty;
RegistryKey rk = Registry.LocalMachine;
RegistryKey key = rk.OpenSubKey(subKeyName);
if (key != null)
{
result = key.GetValue(keyName).ToString();
}
return result;
}
#endregion
///
/// 连接Excel的字符串
///
///
/// 连接Excel的字符串
private string ExcelConnString(string excelVerson, string filePath)
{
string _excelConnString = "";
if (excelVerson == "8.0")
{
_excelConnString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties='Excel 8.0;HDR=Yes'";
}
if (excelVerson == "12.0")
{
_excelConnString = "Provider=Microsoft.Ace.OleDb.12.0;Data Source=" + filePath + ";Extended Properties='Excel 12.0;HDR=Yes'";
}
return _excelConnString;
}
///
/// 调用Win32打开提示框,选择文件
///
/// 返回文件的路径
/// 提示框可选择文件的后缀
private void OpenFile(out string path, string filter = "txt Files|*.txt")
{
path = "";
OpenFileDialog fileDialog = new OpenFileDialog();
fileDialog.Title = "上传文件";
fileDialog.FileName = String.Empty;
fileDialog.Filter = filter;
fileDialog.Multiselect = false;
if (fileDialog.ShowDialog() == true)
{
path = fileDialog.FileName;
}
}
///
/// 调用Win32打开提示框,选择文件(支持多选)
///
/// 返回文件的路径
/// 提示框可选择文件的后缀
private void OpenFile(bool multiSelect, out string path, string filter = "txt Files|*.txt")
{
path = "";
OpenFileDialog fileDialog = new OpenFileDialog();
fileDialog.Title = "上传文件";
fileDialog.FileName = String.Empty;
fileDialog.Filter = filter;
fileDialog.Multiselect = multiSelect;
if (fileDialog.ShowDialog() == true)
{
StringBuilder builder = new StringBuilder();
if (fileDialog.FileNames != null)
{
for (int i = 0; i < fileDialog.FileNames.Length; i++)
{
builder.AppendLine(fileDialog.FileNames[i]);
}
path = builder.ToString();
}
}
}
#endregion
}
}