1216

Datagridview 画行号,第一行显示出行号

读取ini文件比较好的方法

public static string
str_systemconfig_FileName = “config.ini”;

string str = GlobalVar.str_systemconfig_AllPath +
GlobalVar.str_systemconfig_FileName;

INIFile myIniFile = new INIFile(str);

int temp_key = 0;

int temp_section = 0;

GlobalVar.i_strSecsIP =
myIniFile.IniReadValue(GlobalVar.str_systemconfig_section[temp_section],
GlobalVar.str_systemconfig_key[temp_section][temp_key++], “10.73.1.183”);

public class GlobalVar

{

public static StringCollection str_systemconfig_section = new StringCollection()

{

“ConfigInfo”,

};

}

///

/// 读取INI文件

///

///

///

///

public string IniReadValue(string Section, string Key, string Default)

{

Byte[] Buffer = new Byte[65535];

int bufLen =
GetPrivateProfileString(Section, Key, Default, Buffer, Buffer.GetUpperBound(0),
this.path);

//必须设定0(系统默认的代码页)的编码方式,否则无法支持中文

string s =
Encoding.GetEncoding(0).GetString(Buffer);

s = s.Substring(0, bufLen);

return s.Trim();

}

public static StringCollection[] str_systemconfig_key = new
StringCollection[i_systemconfig_section_num]

{

new StringCollection()

{

“SECSIP”,

“SECSPORT”,

}

};

写ini文件

string str = GlobalVar.str_systemconfig_AllPath +
GlobalVar.str_systemconfig_FileName;

INIFile myIniFile = new INIFile(str);

int temp_key = 0;

int temp_section = 0;

myIniFile.IniWriteValue(GlobalVar.str_systemconfig_section[temp_section],
GlobalVar.str_systemconfig_key[temp_section][temp_key++],
GlobalVar.i_strSecsIP);

myIniFile.IniWriteValue(GlobalVar.str_systemconfig_section[temp_section],
GlobalVar.str_systemconfig_key[temp_section][temp_key++],
GlobalVar.i_strSecsPort);

myIniFile.WriteBool(GlobalVar.str_systemconfig_section[temp_section],
GlobalVar.str_systemconfig_key[temp_section][temp_key++],
GlobalVar.i_strUseEDID);

///

/// 写INI文件

///

///

///

///

public void IniWriteValue(string Section, string Key, string Value)

{

try

{

WritePrivateProfileString(Section, Key, Value, this.path);

}

catch

{

throw (new
ApplicationException(“写Ini文件出错”));

}

}

//写Bool

public void WriteBool(string Section, string Ident, bool Value)

{

IniWriteValue(Section, Ident,
Convert.ToString(Value));

}

//读整数

public int ReadInteger(string Section, string Ident, int Default)

{

string intStr =
IniReadValue(Section, Ident, Convert.ToString(Default));

try

{

return
Convert.ToInt32(intStr);

}

catch (Exception ex)

{

Console.WriteLine(ex.Message);

return Default;

}

}

//写整数

public void WriteInteger(string Section, string Ident, int Value)

{

IniWriteValue(Section, Ident,
Value.ToString());

}

//读double

public double Readdouble(string Section, string Ident, double Default)

{

string intStr =
IniReadValue(Section, Ident, Convert.ToString(Default));

try

{

return
Convert.ToDouble(intStr);

}

catch (Exception ex)

{

Console.WriteLine(ex.Message);

return Default;

}

}

//写double

public void Writedouble(string Section, string Ident, double Value)

{

IniWriteValue(Section, Ident,
Value.ToString());

}

///

/// 删除ini文件下所有段落

///

public void ClearAllSection()

{

IniWriteValue(null, null, null);

}

///

/// 删除ini文件下personal段落下的所有键

///

///

public void ClearSection(string Section)

{

IniWriteValue(Section, null, null);

}

//删除某个Section下的键

public void DeleteKey(string Section, string Ident)

{

WritePrivateProfileString(Section,
Ident, null, this.path);

}

//读取指定的Section的所有Value到列表中

public StringCollection ReadSectionValues(string Section,
NameValueCollection Values)

{

StringCollection KeyList = new StringCollection();

KeyList = ReadSection(Section);

Values.Clear();

foreach (string key in KeyList)

{

Values.Add(key,
IniReadValue(Section, key, “”));

}

return KeyList;

}

拆箱

///

/// 系统时间转换成unix时间

///

///

///

public static int DateTimeToTime_t(DateTime dateTime)

{

DateTime dt1 =
TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));

TimeSpan ts = dateTime - dt1;

int Result = (int)ts.TotalSeconds;

return Result;

}

public static decimal ObjectToInt(object value)

{

if (value == null)

{

return 0;

}

decimal result = 0;

if (decimal.TryParse(value.ToString(),
out result))

{

return result;

}

return 0;

}

public static float ObjectToFloat(object value)

{

if (value == null)

{

return 0;

}

float result = 0;

if (float.TryParse(value.ToString(),
out result))

{

return result;

}

return 0;

}

public static string SqliteEscape(string tableName)

{

tableName = “_” + tableName;

tableName = tableName.Replace("’", “_”);

tableName = tableName.Replace("+", “_”);

tableName = tableName.Replace("[", “_”);

tableName = tableName.Replace("]", “_”);

tableName = tableName.Replace("(", “(”);

tableName = tableName.Replace(")", “)”);

tableName = tableName.Replace("-", “_”);

tableName = tableName.Replace(".", “_”);

tableName = tableName.Replace("@", “_”);

tableName = tableName.Replace("#", “_”);

tableName = tableName.Replace("%", “_”);

tableName = tableName.Replace("^", “_”);

tableName = tableName.Replace("&", “_”);

tableName = tableName.Replace("!", “_”);

tableName = tableName.Replace(" ", “_”);

return tableName;

}

public static void ButtonEdit_Click(ButtonEdit tt)

{

tt.Text = GetFilePath(tt.Text);

}

private static string GetFilePath(string oldttText)

{

string resultFilePath = “”;

FolderBrowserDialog folderDlg = new
FolderBrowserDialog();

if
(Directory.Exists(oldttText))

{

folderDlg.SelectedPath =
oldttText;

}

else

{

folderDlg.SelectedPath = “D:\”;

}

folderDlg.ShowDialog();

string str = “”;

if
(folderDlg.SelectedPath != “”)

{

str = folderDlg.SelectedPath;

if (IsDriveC(ref str))

{

MessageBox.Show(“请选择除C盘以外的路径!”);

return “”;

}

string str1 =
str.Substring(str.Length - 1, 1);

if (str1 == “\”)

{

resultFilePath = str;

}

else

{

resultFilePath = str + “\”;

}

}

return resultFilePath;

}

public static double ObjectToDouble(object value)

{

try

{

if (value == null || value ==
DBNull.Value)

{

return 0.0;

}

switch
(value.GetType().ToString())

{

case “System.String”:

return Double.Parse((string)value);

case “System.Int64”:

return Double.Parse(((long)value).ToString());

case “System.Int32”:

return Double.Parse(((int)value).ToString());

case “System.Boolean”:

return 0.0;

case “System.Double”:

return (int)System.Math.Round((double)value, 0);

case “System.DateTime”:

return 0.0;

case “System.Decimal”:

return (double)Convert.ToDecimal(value);

default:

return 0;

}

}

catch

{

return 0.0;

}

}

public static string ObjectToString(Object obj)

{

if (obj == null)

{

return “”;

}

switch
(obj.GetType().ToString())

{

case “System.String”:

return obj.ToString();

case “System.DateTime”:

return
((DateTime)obj).ToLongDateString();

case “System.Int32”:

return
((Int32)obj).ToString();

case “System.Int64”:

return
((Int64)obj).ToString();

case “System.Double”:

return ((double)obj).ToString();

case “System.IO.MemoryStream”:

Stream s = (Stream)obj;

StreamReader sr = new StreamReader(s);

string myString = string.Empty;

while (sr.Peek() > -1)

{

string input =
sr.ReadLine();

myString += input;

}

return myString;

case “System.Byte[]”:

return
Encoding.UTF8.GetString((byte[])obj);

case “System.Boolean”:

if ((bool)obj == false)

return “false”;

else return “true”;

default:

return null;

}

}

数据库操作相关

#region 执行增、删、改操作

///

/// 执行增、删、改操作

///

/// sql语句

/// 连接字符串

/// 返回值:-1表示出现异常

public static int Update(string sql, string connString)

{

MySqlConnection conn = new
MySqlConnection(connString);

MySqlCommand cmd = new MySqlCommand(sql,
conn);

try

{

conn.Open();

return
cmd.ExecuteNonQuery();

}

catch (Exception ex)

{

throw ex;

}

finally

{

conn.Close();

}

}

#endregion

#region 返回单行查询结果

///

/// 返回单行查询结果

///

/// sql语句

/// 连接字符串

/// 返回值:null表示出现异常

public static object GetSingleResult(string sql, string connString)

{

MySqlConnection conn = new
MySqlConnection(connString);

MySqlCommand cmd = new MySqlCommand(sql,
conn);

try

{

conn.Open();

return
cmd.ExecuteScalar();

}

catch (Exception ex)

{

throw ex;

}

finally

{

conn.Close();

}

}

#endregion

#region 同时执行多条查询语句,并将结果填充到对应的DataTable里面,读取时可以根据表的名称访问DataTable

///

/// 同时执行多条查询语句,并将结果填充到对应的DataTable里面,读取时可以根据表的名称访问DataTable

///

/// 使用Dictionary<string, string>封装对一个SQL语句和数据表的名称

/// 连接字符串

/// 返回值:null表示出现异常;返回一个包含若干个数据表的数据集

public static DataSet GetDataSet(Dictionary<string, string> sqlDic, string connString)

{

MySqlConnection conn = new
MySqlConnection(connString);

MySqlCommand cmd = new MySqlCommand();

cmd.Connection = conn;

MySqlDataAdapter da = new
MySqlDataAdapter(cmd);

DataSet ds = new DataSet();

try

{

conn.Open();

foreach (string tableName in sqlDic.Keys)

{

cmd.CommandText =
sqlDic[tableName];

da.Fill(ds, tableName);

}

return ds;

}

catch (Exception ex)

{

throw ex;

}

finally

{

conn.Close();

}

}

#endregion

#region 基于ADO.NET事务提交多条增删改SQL语句

///

/// 基于ADO.NET事务提交多条增删改SQL语句

///

/// sql语句集合

/// 连接字符串

/// 返回是否执行成功

public static bool UpdateByTran(List sqlList, string connString, ref string excuteResult)

{

MySqlConnection conn = new
MySqlConnection(connString);

MySqlCommand cmd = new MySqlCommand();

cmd.Connection = conn;

try

{

conn.Open();

cmd.Transaction =
conn.BeginTransaction();

foreach (string sql in sqlList)

{

excuteResult += (“执行语句:” + sql + “\r\n”);

cmd.CommandText = sql;

int ret =
cmd.ExecuteNonQuery();

excuteResult += (“受影响行数:” + ret + “\r\n”);

}

cmd.Transaction.Commit();

return true;

}

catch (Exception ex)

{

if (cmd.Transaction !=
null)

{

cmd.Transaction.Rollback();

}

throw ex;

}

finally

{

if (cmd.Transaction !=
null)

{

cmd.Transaction = null;

}

conn.Close();

}

}

#endregion

#region 获取服务器时间

public static DateTime GetDBServerTime(string connString)

{

string sql = “select getdate()”;

return
Convert.ToDateTime(GetSingleResult(sql, connString));

}

#endregion

#region 调用存储过程插入数据

///

/// 调用存储过程插入数据

///

/// 存储过程名称

/// 参数

/// 数据库连接字符串

///

public static int UpdateByProcedure(string storeProcedureName,
MySqlParameter[] param, string connString)

{

MySqlConnection conn = new
MySqlConnection(connString);

MySqlCommand cmd = new MySqlCommand();

cmd.Connection = conn;

cmd.CommandType =
CommandType.StoredProcedure;

cmd.CommandText =
storeProcedureName;

try

{

conn.Open();

cmd.Parameters.AddRange(param);

return
cmd.ExecuteNonQuery();

}

catch (Exception ex)

{

throw ex;

}

finally

{

conn.Close();

}

}

///

/// 创建数据库

///

/// 数据库路径

/// sql语句

///

public static int CreateDatabase(string databasePath, string sql)

{

string dbPath = “data source=” + databasePath;

if
(!File.Exists(databasePath))

{

SQLiteConnection.CreateFile(databasePath);

}

SQLiteConnection conn = new
SQLiteConnection(dbPath);

SQLiteCommand cmdCreateTable = new SQLiteCommand(sql,
conn);

try

{

conn.Open();

return
cmdCreateTable.ExecuteNonQuery();

}

catch (Exception)

{

return -1;

}

finally

{

conn.Close();

}

}

///

/// 执行增、删、改操作

///

///

///

///

public static int Update(string databasePath, string sql)

{

string dbPath = “Data Source=” + databasePath;

SQLiteConnection conn = new
SQLiteConnection(dbPath);

SQLiteCommand cmd = new SQLiteCommand(sql,
conn);

try

{

conn.Open();

return
cmd.ExecuteNonQuery();

}

catch (Exception ex)

{

return -2;

}

finally

{

conn.Close();

}

}

///

/// 插入数据

///

/// 数据库路径

/// sql语句

///

public static int InsertData(string databasePath, string sql)

{

string dbPath = “Data Source=” + databasePath;

SQLiteConnection conn = new
SQLiteConnection(dbPath);

SQLiteCommand cmdInsert = new SQLiteCommand(sql,
conn);

try

{

conn.Open();

return
cmdInsert.ExecuteNonQuery();

}

catch (Exception)

{

return -1;

}

finally

{

conn.Close();

}

}

///

/// 返回单行查询结果

///

///

///

///

public static object GetSingleResult(string sql, string databasePath)

{

string dbPath = “Data Source=” + databasePath;

SQLiteConnection conn = new
SQLiteConnection(dbPath);

SQLiteCommand cmdInsert = new SQLiteCommand(sql,
conn);

try

{

conn.Open();

return
cmdInsert.ExecuteScalar();

}

catch (Exception)

{

return -1;

}

finally

{

conn.Close();

}

}

///

/// 基于事务执行多条sql语句

///

/// 数据库路径

/// sql语句

///

public static bool UpdateByTran(List sqlList, string databasePath, ref string excuteResult)

{

string dbPath = “Data Source=” + databasePath;

SQLiteConnection conn = new
SQLiteConnection(dbPath);

SQLiteCommand cmd = new SQLiteCommand();

cmd.Connection = conn;

try

{

conn.Open();

cmd.Transaction =
conn.BeginTransaction();

foreach (string sql in sqlList)

{

excuteResult += (“执行语句:” + sql + “\r\n”);

cmd.CommandText = sql;

int ret =
cmd.ExecuteNonQuery();

excuteResult += (“受影响行数:” + ret + “\r\n”);

}

cmd.Transaction.Commit();

return true;

}

catch (Exception)

{

if (cmd.Transaction !=
null)

{

cmd.Transaction.Rollback();

}

return false;

}

finally

{

if (cmd.Transaction !=
null)

{

cmd.Transaction = null;

}

conn.Close();

}

}

///

/// 同时执行多条查询语句,将结果填充到对应的datatable里面

///

/// 数据库路径

/// sql语句

///

public static DataSet GetDataSet(Dictionary<string, string> sqlDic, string databasePath)

{

string dbPath = “Data Source=” + databasePath;

SQLiteConnection conn = new
SQLiteConnection(dbPath);

SQLiteCommand cmd = new SQLiteCommand();

cmd.Connection = conn;

SQLiteDataAdapter da = new
SQLiteDataAdapter(cmd);

DataSet ds = new DataSet();

try

{

conn.Open();

foreach (string tableName in sqlDic.Keys)

{

cmd.CommandText =
sqlDic[tableName];

da.Fill(ds, tableName);

}

return ds;

}

catch (Exception e)

{

string ex = e.ToString();

return null;

}

finally

{

conn.Close();

}

}

public DataSet GetYieldAndReportInfo(string tableName, string connString,
DataBrowse dataBrowse)

{

string sql = $“SELECT
SNResult,AOIResult,AFResult,EDIDResult,IDDResult,WorkStation,InsertTime FROM {tableName} WHERE 1=1”;

sql += " ORDER BY InsertTime DESC;";

string sqlReport = $“SELECT * FROM {tableName} WHERE PanelID = ‘{dataBrowse.PanelID}’ ORDER BY InsertTime DESC LIMIT 1;”;

Dictionary<string, string> sqlDic = new Dictionary<string, string>() { { “Total”, sql }, { “Report”, sqlReport } };

try

{

DataSet dataSet =
MySQLHelper.GetDataSet(sqlDic, connString);

return dataSet;

}

catch (Exception ex)

{

LogService.LogMessage(LogType.DMSErrorMsg.ToString(),
“读取GetYieldAndReportInfo异常:” + ex.ToString());

return null;

}

}

DataSet dataset = gammaService.GetJYPanelInfoIDpk(Connstr, lcsMes[j]);

if (dataset != null)

{

DataTable dataTable =
dataset.Tables[“Total”];

}

CSV文件写

string reportName = string.Format("{0:yyyyMMdd}", DateTime.Now) + “.csv”;

if (IsFileUsing(path +
$"//{reportName}"))

{

path += “_Temp”;

}

if
(!Directory.Exists(path))

{

Directory.CreateDirectory(path);

}

path += $"//{reportName}";

if
(!File.Exists(path))

{

string content = “”;

content = “线别,操作员,型号,时间,二维码,工位,检测结果,错误描述,检测耗时,缺陷类型,X像素坐标,Y像素坐标,X距离坐标,Y距离坐标,W长度,H高度,缺陷九宫格,检测参数,缺陷检出相机,缺陷画面,apiTT,产品像素坐标X,产品像素坐标Y”;

try

{

File.AppendAllText(path,
content + “\r\n”, Encoding.UTF8);

}

catch (Exception ex)

{

LogService.LogMessage(LogType.DMSErrorMsg.ToString(), “创建Report异常:” + ex.ToString());

}

}

直接datatable

ExportFileService exportFileService = new
ExportFileService();

public bool DataTableExportCSV(DataTable dt, string savaPath, string strName)

{

return
exportFileService.DataTableExportCSV(dt, savaPath, strName);

}

Chart统计表格操作

// Chart显示功能

Dictionary<string, Color> chartColor = new Dictionary<string, Color>();

List ColorLists = new List() { Color.Aquamarine,
Color.LightSalmon, Color.LightSteelBlue,

Color.LightYellow ,Color.Bisque
,Color.Gold ,Color.GreenYellow ,Color.SkyBlue ,Color.SlateGray ,Color.Lavender
, Color.Thistle,Color.Wheat ,Color.Tomato ,Color.Turquoise ,
Color.Teal,Color.Tan };

public void ShowChart(Chart chart, List dataList,
SeriesChartType chartType = SeriesChartType.Pie)

{

chart.Series.Clear();

System.Windows.Forms.DataVisualization.Charting.Series series1 = new
System.Windows.Forms.DataVisualization.Charting.Series();

series1.ChartType = chartType;

chart.Series.Add(series1);

for (int i = 0; i <
dataList.Count; i++)

{

Color color = Color.Green;

string text =
dataList[i].Text;

try

{

if
(!chartColor.ContainsKey(text))

{

switch (text)

{

case “OK”:

color =
Color.LightGreen;

break;

case “NG”:

color =
Color.Yellow;

break;

case “PASS”:

color = Color.Red;

break;

default:

color =
ColorLists[chartColor.Count];

break;

}

chartColor.Add(text,
color);

}

else

{

color =
chartColor[text];

}

}

catch { }

double value =
dataList[i].Value;

series1.Points.AddXY(text,
value);

series1.Points[i].LabelToolTip
= text + “(” + value.ToString() + “)”;

series1.Points[i].ToolTip =
text + “(” + value.ToString() + “)”;

series1.Points[i].Label = “#AXISLABEL”;//设置标签显示的内容=X轴内容+value

series1.Points[i].LegendText = “#AXISLABEL(#VAL)(#PERCENT)”;

series1[“PieLabelStyle”] = “Inside”; //在外侧显示Lable

series1[“PieLineColor”] = “Black”;//绘制连线

series1.Points[i].Color =
color;

}

}

public class ChartData

{

public ChartData() { }

public ChartData(string text, double value)

{

this.Text = text;

this.Value = value;

}

///

/// 显示的文本

///

public string Text { get; set; }

///

/// 显示的值

///

public double Value { get; set; }

}

List GMChartData = new
List();

if
(myReportData.GAMAYieldData.GMOKCount > 0)

{

GMChartData.Add(new ChartData()

{

Text = “OK”,

Value =
myReportData.GAMAYieldData.GMOKCount,

});

}

if
(myReportData.GAMAYieldData.GMNGCount > 0)

{

GMChartData.Add(new ChartData()

{

Text = “NG”,

Value =
myReportData.GAMAYieldData.GMNGCount,

});

}

if
(myReportData.GAMAYieldData.GMPASSCount > 0)

{

GMChartData.Add(new ChartData()

{

Text = “PASS”,

Value =
myReportData.GAMAYieldData.GMPASSCount,

});

}

ShowChart(this.chart_GAMMA, GMChartData);

XML文件操作

public class
XML

{

#region XML文档节点查询和读取

///

/// 选择匹配XPath表达式的第一个节点XmlNode.

///

///

XML文档完全文件名(包含物理路径)

///

要匹配的XPath表达式(例如:"//节点名//子节点名")

///
返回XmlNode

public
static XmlNode GetXmlNodeByXpath(XmlDocument xmlDoc, string xpath)

{

//XmlDocument xmlDoc = new XmlDocument();

try

{

//xmlDoc.Load(xmlFileName);
//加载XML文档

XmlNode xmlNode = xmlDoc.SelectSingleNode(xpath);

return xmlNode;

}

catch
(Exception ex)

{

return null;

//throw ex; //这里可以定义你自己的异常处理

}

}

///

/// 选择匹配XPath表达式的节点列表XmlNodeList.

///

///

XML文档完全文件名(包含物理路径)

///

要匹配的XPath表达式(例如:"//节点名//子节点名")

///
返回XmlNodeList

public
static XmlNodeList GetXmlNodeListByXpath(string xmlFileName, string xpath)

{

XmlDocument xmlDoc = new XmlDocument();

try

{

xmlDoc.Load(xmlFileName); //加载XML文档

XmlNodeList xmlNodeList = xmlDoc.SelectNodes(xpath);

return xmlNodeList;

}

catch
(Exception ex)

{

return null;

//throw ex; //这里可以定义你自己的异常处理

}

}

///

/// 选择匹配XPath表达式的第一个节点的匹配xmlAttributeName的属性XmlAttribute.

///

///

XML文档完全文件名(包含物理路径)

///

要匹配的XPath表达式(例如:"//节点名//子节点名

///

要匹配xmlAttributeName的属性名称

///
返回xmlAttributeName

public
static XmlAttribute GetXmlAttribute(XmlDocument xmlDoc, string xpath, string
xmlAttributeName)

{

string
content = string.Empty;

//XmlDocument xmlDoc = new XmlDocument();

XmlAttribute xmlAttribute = null;

try

{

//xmlDoc.Load(xmlFileName); //加载XML文档

XmlNode xmlNode = xmlDoc.SelectSingleNode(xpath);

if
(xmlNode != null)

{

if (xmlNode.Attributes.Count > 0)

{

xmlAttribute = xmlNode.Attributes[xmlAttributeName];

}

}

}

catch
(Exception ex)

{

throw ex; //这里可以定义你自己的异常处理

}

return
xmlAttribute;

}

///

/// 选择匹配XPath表达式的第一个节点的匹配xmlAttributeName的属性XmlAttribute.

///

///

XML文档完全文件名(包含物理路径)

///

要匹配的XPath表达式(例如:"//节点名//子节点名

///

要匹配xmlAttributeName的属性名称

///
返回xmlAttributeName

public
static string GetXmlByAttribute(string xmlFileName, string xpath, string name,
string xmlAttributeName, string xmlAttributeValues)

{

string
content = string.Empty;

XmlDocument xmlDoc = new XmlDocument();

try

{

xmlDoc.Load(xmlFileName); //加载XML文档

//主要

XmlNodeList xlist = xmlDoc.SelectNodes(xpath);

XmlNode xmlNode = xlist.Cast().Where(o =>
o.Attributes.Cast().FirstOrDefault(a => a.Name ==
xmlAttributeName && a.Value == xmlAttributeValues) != null).FirstOrDefault();

//XmlNode xmlNode = xmlDoc.SelectSingleNode(xpath);

if
(xmlNode != null)

{

foreach (XmlNode node in xmlNode.ChildNodes)

{

if (node.Name.ToLower() == name.ToLower())

{

//存在此节点则返回InnerText

content =
node.InnerText;

break;

}

}

}

}

catch
(Exception ex)

{

throw ex; //这里可以定义你自己的异常处理

}

return
content;

}

#endregion

#region XML文档创建和节点或属性的添加、修改

///

/// 创建一个XML文档

///

///

XML文档完全文件名(包含物理路径)

///

XML文档根节点名称(须指定一个根节点名称)

///

XML文档版本号(必须为:"1.0")

///

XML文档编码方式

/// 该值必须是"yes"或"no",如果为null,Save方法不在XML声明上写出独立属性

///
成功返回true,失败返回false

public
static bool CreateXmlDocument(string xmlFileName, string rootNodeName, string
version, string encoding, string standalone)

{

bool
isSuccess = false;

try

{

XmlDocument xmlDoc = new XmlDocument();

XmlDeclaration xmlDeclaration = xmlDoc.CreateXmlDeclaration(version,
encoding, standalone);

XmlNode root = xmlDoc.CreateElement(rootNodeName);

xmlDoc.AppendChild(xmlDeclaration);

xmlDoc.AppendChild(root);

xmlDoc.Save(xmlFileName);

isSuccess = true;

}

catch
(Exception ex)

{

throw ex; //这里可以定义你自己的异常处理

}

return
isSuccess;

}

///

/// 依据匹配XPath表达式的第一个节点来创建它的子节点(如果此节点已存在则追加一个新的同名节点

///

/// XML文档完全文件名(包含物理路径)

///

要匹配的XPath表达式(例如:"//节点名//子节点名

///

要匹配xmlNodeName的节点名称

///

节点文本值

/// 要匹配xmlAttributeName的属性名称

///

属性值

///
成功返回true,失败返回false

public
static bool CreateXmlNodeByXPath(XmlDocument xmlDoc, string xpath, string
xmlNodeName, string innerText, string xmlAttributeName, string value)

{

bool
isSuccess = false;

//XmlDocument xmlDoc = new XmlDocument();

try

{

//xmlDoc.Load(xmlFileName); //加载XML文档

XmlNode xmlNode =
xmlDoc.SelectSingleNode(xpath);

if
(xmlNode != null)

{

//存不存在此节点都创建

XmlElement subElement = xmlDoc.CreateElement(xmlNodeName);

subElement.InnerXml = innerText;

//如果属性和值参数都不为空则在此新节点上新增属性

if (!string.IsNullOrEmpty(xmlAttributeName) &&
!string.IsNullOrEmpty(value))

{

XmlAttribute xmlAttribute = xmlDoc.CreateAttribute(xmlAttributeName);

xmlAttribute.Value = value;

subElement.Attributes.Append(xmlAttribute);

}

xmlNode.AppendChild(subElement);

}

//xmlDoc.Save(xmlFileName); //保存到XML文档

isSuccess = true;

}

catch
(Exception ex)

{

throw ex; //这里可以定义你自己的异常处理

}

return
isSuccess;

}

///

/// 依据匹配XPath表达式的第一个节点来创建或更新它的子节点(如果节点存在则更新,不存在则创建)

///

///

XML文档完全文件名(包含物理路径)

///

要匹配的XPath表达式(例如:"//节点名//子节点名

///

要匹配xmlNodeName的节点名称

///

节点文本值

///
成功返回true,失败返回false

public
static bool CreateOrUpdateXmlNodeByXPath(string xmlFileName, string xpath,
string xmlNodeName, string innerText)

{

bool
isSuccess = false;

bool
isExistsNode = false;//标识节点是否存在

XmlDocument xmlDoc = new XmlDocument();

try

{

xmlDoc.Load(xmlFileName); //加载XML文档

//XmlNodeList xlist = xmlDoc.SelectNodes(xpath);

//XmlNode xmlNode = xlist.Cast().Where(o =>
o.InnerText == innerText).FirstOrDefault();

XmlNode xmlNode = xmlDoc.SelectSingleNode(xpath);

if
(xmlNode != null)

{

//遍历xpath节点下的所有子节点

foreach (XmlNode node in xmlNode.ChildNodes)

{

//XmlAttribute att = node.Attributes.Cast().Where(o
=> o.Name == innerText).FirstOrDefault();

if (node.Name.ToLower() == xmlNodeName.ToLower())

{

//存在此节点则更新

node.InnerXml =
innerText;

isExistsNode =
true;

break;

}

}

if (!isExistsNode)

{

//不存在此节点则创建

XmlElement subElement = xmlDoc.CreateElement(xmlNodeName);

subElement.InnerXml = innerText;

xmlNode.AppendChild(subElement);

}

}

xmlDoc.Save(xmlFileName); //保存到XML文档

isSuccess = true;

}

catch
(Exception ex)

{

throw ex; //这里可以定义你自己的异常处理

}

return isSuccess;

}

///

/// 依据匹配XPath表达式的第一个节点来创建或更新它的子节点(如果节点存在则更新,不存在则创建)

///

///

XML文档完全文件名(包含物理路径)

///

要匹配的XPath表达式(例如:"//节点名//子节点名

///

要匹配xmlNodeName的节点名称

///

节点文本值

///
成功返回true,失败返回false

public
static bool CreateOrUpdateXmlNodeByXPath(string xmlFileName, string xpath,
string xmlNodeName, string innerText, string XmlAttributeName, string
XmlAttributeValues)

{

bool
isSuccess = false;

bool
isExistsNode = false;//标识节点是否存在

XmlDocument xmlDoc = new XmlDocument();

try

{

xmlDoc.Load(xmlFileName); //加载XML文档

XmlNode xmlNode = xmlDoc.SelectSingleNode(xpath);

if
(xmlNode != null)

{

//遍历xpath节点下的所有子节点

foreach (XmlNode node in xmlNode.ChildNodes)

{

XmlAttribute att = node.Attributes.Cast().Where(o
=> o.Name == XmlAttributeName && o.Value ==
XmlAttributeValues).FirstOrDefault();

if (att != null && node.Name.ToLower() == xmlNodeName.ToLower())

{

//存在此节点则更新

node.InnerXml =
innerText;

isExistsNode = true;

#region      //遍历xpath节点中的所有属性

bool
isExistsAttribute = false;

foreach
(XmlAttribute attribute in node.Attributes)

{

if
(attribute.Name.ToLower() == XmlAttributeName.ToLower())

{

//节点中存在此属性则更新

attribute.Value = XmlAttributeValues;

isExistsAttribute = true;

break;

}

}

if
(!isExistsAttribute)

{

//节点中不存在此属性则创建

XmlAttribute
xmlAttribute = xmlDoc.CreateAttribute(XmlAttributeName);

xmlAttribute.Value = XmlAttributeValues;

node.Attributes.Append(xmlAttribute);

}

#endregion

break;

}

}

if (!isExistsNode)

{

//不存在此节点则创建

XmlElement subElement = xmlDoc.CreateElement(xmlNodeName);

subElement.InnerXml = innerText;

XmlAttribute xmlAttribute = xmlDoc.CreateAttribute(XmlAttributeName);

xmlAttribute.Value = XmlAttributeValues;

subElement.Attributes.Append(xmlAttribute);

xmlNode.AppendChild(subElement);

}

}

xmlDoc.Save(xmlFileName); //保存到XML文档

isSuccess = true;

}

catch
(Exception ex)

{

throw ex; //这里可以定义你自己的异常处理

}

return
isSuccess;

}

///

/// 依据匹配XPath表达式的第一个节点来创建或更新它的子节点(如果节点存在则更新,不存在则创建)

///

///

XML文档完全文件名(包含物理路径)

///

要匹配的XPath表达式(例如:"//节点名//子节点名

///

要匹配xmlNodeName的节点名称

///

节点文本值

///

指定父节点文本值

///
成功返回true,失败返回false

public
static bool CreateOrUpdateXmlNodeByXPath(XmlDocument xmlDoc, string xpath,
string xmlNodeName, string innerText)

{

bool
isSuccess = false;

bool
isExistsNode = false;//标识节点是否存在

//XmlDocument xmlDoc = new XmlDocument();

try

{

//xmlDoc.Load(xmlFileName); //加载XML文档

//XmlNodeList xlist = xmlDoc.SelectNodes(xpath);

//主要

//XmlNode xmlNode = xlist.Cast().Where(o =>
o.Attributes.Cast().FirstOrDefault(a => a.Name ==
“CameraCount” && a.Value == parentAttributevalues) !=
null).FirstOrDefault();

XmlNode xmlNode = xmlDoc.SelectSingleNode(xpath);

if
(xmlNode != null)

{

//遍历xpath节点下的所有子节点

foreach (XmlNode node in xmlNode.ChildNodes)

{

if (node.Name.ToLower() == xmlNodeName.ToLower())

{

//存在此节点则更新

node.InnerXml =
innerText;

isExistsNode =
true;

break;

}

}

if (!isExistsNode)

{

//不存在此节点则创建

XmlElement subElement = xmlDoc.CreateElement(xmlNodeName);

subElement.InnerXml = innerText;

xmlNode.AppendChild(subElement);

}

}

//xmlDoc.Save(xmlFileName); //保存到XML文档

isSuccess = true;

}

catch
(Exception ex)

{

throw ex; //这里可以定义你自己的异常处理

}

return
isSuccess;

}

///

/// 依据匹配XPath表达式的第一个节点来创建或更新它的属性(如果属性存在则更新,不存在则创建)

///

///

XML文档完全文件名(包含物理路径)

///

要匹配的XPath表达式(例如:"//节点名//子节点名

///

要匹配xmlAttributeName的属性名称

///

属性值

///
成功返回true,失败返回false

public
static bool CreateOrUpdateXmlAttributeByXPath(XmlDocument xmlDoc, string xpath,
string xmlAttributeName, string value)

{

bool
isSuccess = false;

bool
isExistsAttribute = false;//标识属性是否存在

//XmlDocument xmlDoc = new XmlDocument();

try

{

//xmlDoc.Load(xmlFileName); //加载XML文档

XmlNode xmlNode = xmlDoc.SelectSingleNode(xpath);

if
(xmlNode != null)

{

//遍历xpath节点中的所有属性

foreach (XmlAttribute attribute in xmlNode.Attributes)

{

if (attribute.Name.ToLower() == xmlAttributeName.ToLower())

{

//节点中存在此属性则更新

attribute.Value = value;

isExistsAttribute =
true;

break;

}

}

if (!isExistsAttribute)

{

//节点中不存在此属性则创建

XmlAttribute xmlAttribute = xmlDoc.CreateAttribute(xmlAttributeName);

xmlAttribute.Value = value;

xmlNode.Attributes.Append(xmlAttribute);

}

}

//xmlDoc.Save(xmlFileName); //保存到XML文档

isSuccess = true;

}

catch
(Exception ex)

{

throw ex; //这里可以定义你自己的异常处理

}

return isSuccess;

}

#endregion

#region XML文档节点或属性的删除

///

/// 删除匹配XPath表达式的第一个节点(节点中的子元素同时会被删除)

///

///

XML文档完全文件名(包含物理路径)

///

要匹配的XPath表达式(例如:"//节点名//子节点名

///
成功返回true,失败返回false

public
static bool DeleteXmlNodeByXPath(XmlDocument xmlDoc, string xpath)

{

bool
isSuccess = false;

try

{

XmlNode xmlNode = xmlDoc.SelectSingleNode(xpath);

if
(xmlNode != null)

{

//删除节点

xmlNode.ParentNode.RemoveChild(xmlNode);

}

isSuccess = true;

}

catch
(Exception ex)

{

throw ex; //这里可以定义你自己的异常处理

}

return
isSuccess;

}

///

/// 删除匹配XPath表达式的第一个节点中的匹配参数xmlAttributeName的属性

///

///

XML文档完全文件名(包含物理路径)

///

要匹配的XPath表达式(例如:"//节点名//子节点名

///

要删除的xmlAttributeName的属性名称

/// 成功返回true,失败返回false

public
static bool DeleteXmlAttributeByXPath(string xmlFileName, string xpath, string
xmlAttributeName)

{

bool
isSuccess = false;

bool
isExistsAttribute = false;

XmlDocument xmlDoc = new XmlDocument();

try

{

xmlDoc.Load(xmlFileName); //加载XML文档

XmlNode xmlNode = xmlDoc.SelectSingleNode(xpath);

XmlAttribute xmlAttribute = null;

if
(xmlNode != null)

{

//遍历xpath节点中的所有属性

foreach (XmlAttribute attribute in xmlNode.Attributes)

{

if (attribute.Name.ToLower() == xmlAttributeName.ToLower())

{

//节点中存在此属性

xmlAttribute =
attribute;

isExistsAttribute =
true;

break;

}

}

if (isExistsAttribute)

{

//删除节点中的属性

xmlNode.Attributes.Remove(xmlAttribute);

}

}

xmlDoc.Save(xmlFileName); //保存到XML文档

isSuccess = true;

}

catch
(Exception ex)

{

throw ex; //这里可以定义你自己的异常处理

}

return
isSuccess;

}

///

/// 删除匹配XPath表达式的第一个节点中的所有属性

///

///

XML文档完全文件名(包含物理路径)

///

要匹配的XPath表达式(例如:"//节点名//子节点名

///
成功返回true,失败返回false

public
static bool DeleteAllXmlAttributeByXPath(string xmlFileName, string xpath)

{

bool
isSuccess = false;

XmlDocument xmlDoc = new XmlDocument();

try

{

xmlDoc.Load(xmlFileName); //加载XML文档

XmlNode xmlNode = xmlDoc.SelectSingleNode(xpath);

if
(xmlNode != null)

{

//遍历xpath节点中的所有属性

xmlNode.Attributes.RemoveAll();

}

xmlDoc.Save(xmlFileName); //保存到XML文档

isSuccess = true;

}

catch
(Exception ex)

{

throw ex; //这里可以定义你自己的异常处理

}

return
isSuccess;

}

#endregion

#region 通过反射写入节点通用方法

///

/// 通过反射写入节点通用方法

///

///

///

///

///

///

是否将子集合写入

public
static void WriteNodeByProperty(T obj, XmlDocument xmlDoc, string
xpath, bool isList)

{

PropertyInfo[] properties = obj.GetType().GetProperties();

foreach (PropertyInfo info in properties)

{

if
(info.PropertyType.IsGenericType && isList)

{

dynamic value = obj.GetType().GetProperty(info.Name).GetValue(obj);

int count = 0;

foreach (var item in value)

{

CreateOrUpdateXmlNodeByXPath(xmlDoc, xpath, info.Name + count,
“”);

WriteNodeByProperty(item, xmlDoc, xpath + “//” + info.Name +
count++, isList);

}

}

else

{

if (!info.PropertyType.IsConstructedGenericType)

{

string tt =
obj.GetType().GetProperty(info.Name).GetValue(obj).ToString();

CreateOrUpdateXmlNodeByXPath(xmlDoc, xpath, info.Name, tt);

}

}

}

}

#endregion

#region 通过反射读取节点通用方法

///

/// 通过反射读取节点通用方法

///

///

///

///

///

///

public
static T ReadNodeByProperty(T obj, XmlDocument xmlDoc, string xpath)

{

PropertyInfo[] properties = obj.GetType().GetProperties();

foreach
(PropertyInfo info in properties)

{

if
(!info.PropertyType.IsGenericType)

{

XmlNode node = GetXmlNodeByXpath(xmlDoc, xpath + “//” +
info.Name);

if (node != null)

{

object value = TypeTranslation(node.InnerText, info.PropertyType);

obj.GetType().GetProperty(info.Name).SetValue(obj, value);

}

}

}

return
obj;

}

#endregion

#region 类型转换方法

///

/// 类型转换方法

///

///

初始值

///

类型

///

private
static object TypeTranslation(string value, Type valuetype)

{

if
(valuetype == typeof(string) || valuetype == typeof(String))

{

return value;

}

object
obj = new object();

try

{

if
(string.IsNullOrEmpty(value))

{

if (valuetype == typeof(int))

{

obj = default(int);

}

else if (valuetype == typeof(double) || valuetype == typeof(Double))

{

obj = default(double);

}

else if (valuetype == typeof(float))

{

obj = default(float);

}

else if (valuetype == typeof(long))

{

obj = default(long);

}

else if (valuetype == typeof(DateTime))

{

obj = default(DateTime);

}

}

else if (valuetype.IsEnum)

{

Type type = Nullable.GetUnderlyingType(valuetype) ?? valuetype;

obj = Enum.Parse(valuetype, value);

}

else

{

obj = valuetype.GetMethod(“Parse”, new Type[] { typeof(string)
}).Invoke(null, new object[] { value });

}

}

catch
(Exception)

{

}

return
obj;

}

#endregion

public
static void DeleteExceptionFile(string path)

{

try

{

if
(File.Exists(path))

{

File.Delete(path);

}

}

catch
(Exception)

{

}

}

}

数据库去重语句

string sql = $“SELECT *
FROM {tableName} b WHERE 1=1”;

if
(dataBrowse.StartTime != -1)

{

sql += $" AND InsertTime>={dataBrowse.StartTime}";

}

if (dataBrowse.EndTime
!= -1)

{

sql += $" AND InsertTime<={dataBrowse.EndTime}";

}

if (!string.IsNullOrEmpty(dataBrowse.PanelID))

{

sql += $" AND PanelID LIKE ‘%{dataBrowse.PanelID}%’";

}

sql += $" AND b.pk_No IN (SELECT e.PNo FROM (select
PanelID,count(*) as count,MAX(pk_No) as PNo from {tableName} group by PanelID
having count = 1) as e)";

sql += " UNION ALL";

sql += $" SELECT * FROM {tableName} b WHERE 1=1";

if
(dataBrowse.StartTime != -1)

{

sql += $" AND InsertTime>={dataBrowse.StartTime}";

}

if (dataBrowse.EndTime
!= -1)

{

sql += $" AND InsertTime<={dataBrowse.EndTime}";

}

if (!string.IsNullOrEmpty(dataBrowse.PanelID))

{

sql += $" AND PanelID LIKE ‘%{dataBrowse.PanelID}%’";

}

sql += $" AND b.pk_No IN (SELECT e.PNo FROM (select
PanelID,count(*) as count,MAX(pk_No) as PNo from {tableName} group by PanelID
having count> 1) as e);";

合并datatable

#region 合并表格

private DataTable MergeDataTable(DataTable dataTable1, DataTable
dataTable2)

{

//DataTable DataTable1 = new DataTable();

//DataTable DataTable2 = new DataTable();

DataTable newDataTable =
dataTable1.Columns.Count > dataTable2.Columns.Count ? dataTable1.Clone() :
dataTable2.Clone();

object[] obj = new object[newDataTable.Columns.Count];

for (int i = 0; i <
dataTable1.Rows.Count; i++)

{

dataTable1.Rows[i].ItemArray.CopyTo(obj, 0);

newDataTable.Rows.Add(obj);

}

for (int i = 0; i <
dataTable2.Rows.Count; i++)

{

dataTable2.Rows[i].ItemArray.CopyTo(obj,
0);

newDataTable.Rows.Add(obj);

}

return newDataTable;

}

ftp下载

// FTP 下载

public static bool FtpFileDownload(string savePath, string fileName, string ftpServerIP, string ftpUserID, string ftpPassword)

{

string ftpServerPath = “ftp://” + ftpServerIP + “:21//” + fileName; //":23"指定的端口,不填默认端口为21

string ftpUser =
ftpUserID;

string ftpPwd =
ftpPassword;

string saveFilePath =
savePath;

FileStream outputStream = null;

FtpWebResponse response = null;

FtpWebRequest reqFTP;

try

{

reqFTP =
(FtpWebRequest)FtpWebRequest.Create(new Uri(ftpServerPath));

reqFTP.Method =
WebRequestMethods.Ftp.DownloadFile;

reqFTP.UseBinary = true;

reqFTP.KeepAlive = false;

reqFTP.Timeout = 3000;

reqFTP.Credentials = new
NetworkCredential(ftpUser, ftpPwd);

response =
(FtpWebResponse)reqFTP.GetResponse();

Stream ftpStream =
response.GetResponseStream();

int bufferSize = 2048;

int readCount;

int ftpFileReadSize =
0;

byte[] buffer = new byte[bufferSize];

readCount =
ftpStream.Read(buffer, 0, bufferSize);

outputStream = new
FileStream(saveFilePath, FileMode.Create);

while (readCount > 0)

{

ftpFileReadSize +=
readCount;

outputStream.Write(buffer,
0, readCount);

readCount =
ftpStream.Read(buffer, 0, bufferSize);

}

ftpStream.Close();

outputStream.Close();

response.Close();

}

catch (Exception ex)

{

LogManager.LogMessage(LogType.SECSErrorMsg, “FtpClient异常:” + ex.Message);

if (outputStream != null)

{

outputStream.Close();

}

if (response != null)

{

response.Close();

}

return false;

}

return true;

}

// 获取FTP文件大小

private long GetFtpFileSize(string fileName, string ftpServerIP, string ftpUserID, string ftpPassword)

{

long fileSize = 0;

string ftpServerPath = “ftp://” + ftpServerIP + “:23” + fileName;

string ftpUser =
ftpUserID;

string ftpPwd =
ftpPassword;

FtpWebResponse response = null;

FtpWebRequest reqFTP;

try

{

reqFTP = (FtpWebRequest)FtpWebRequest.Create(new
Uri(ftpServerPath));

reqFTP.Method =
WebRequestMethods.Ftp.DownloadFile;

reqFTP.UseBinary = true;

reqFTP.KeepAlive = false;

reqFTP.Timeout = 3000;

reqFTP.Credentials = new
NetworkCredential(ftpUser, ftpPwd);

reqFTP.Method =
WebRequestMethods.Ftp.GetFileSize;//要求返回文件大小属性

response =
(FtpWebResponse)reqFTP.GetResponse();

fileSize = response.ContentLength;

response.Close();

}

catch (Exception ex)

{

LogManager.LogMessage(LogType.SECSErrorMsg, “FtpClient异常:” + ex.Message);

if (response != null)

{

response.Close();

}

return -1;

}

return fileSize;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值