基线 SVN r240

SVN-Revision: r240
This commit is contained in:
cyf
2025-02-06 06:46:06 +00:00
commit ab56a9bcf7
5317 changed files with 902274 additions and 0 deletions
+129
View File
@@ -0,0 +1,129 @@
/******************************
* 说明:AES对称加密
* 创建人:龚宇超
* 创建日期:2018-06-21
* 修改人:
* 修改日期:
* 修改备注:
* 版本:1.0.0.0
******************************/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace Lskj.Util
{
/// <summary>
/// AES对称加密
/// </summary>
public class AESUtil
{
private static string key = "lserpasebygyc222";
#region AES加解密
/// <summary>
///AES加密(加密步骤)
///1,加密字符串得到2进制数组;
///2,将2进制数组转为16进制;
///3,进行base64编码
/// </summary>
/// <param name="toEncrypt">要加密的字符串</param>
/// <param name="key">密钥</param>
public static string Encrypt(string toEncrypt)
{
if (string.IsNullOrEmpty(toEncrypt)) return "";
byte[] _key = Encoding.ASCII.GetBytes(key);
byte[] _source = Encoding.UTF8.GetBytes(toEncrypt);
Aes aes = Aes.Create("AES");
aes.Mode = CipherMode.ECB;
aes.Padding = PaddingMode.PKCS7;
aes.Key = _key;
ICryptoTransform cTransform = aes.CreateEncryptor();
byte[] cryptData = cTransform.TransformFinalBlock(_source, 0, _source.Length);
string hexCryptString = Hex_2To16(cryptData);
byte[] hexCryptData = Encoding.UTF8.GetBytes(hexCryptString);
return Convert.ToBase64String(hexCryptData);
}
/// <summary>
/// AES解密(解密步骤)
/// 1,将BASE64字符串转为16进制数组
/// 2,将16进制数组转为字符串
/// 3,将字符串转为2进制数据
/// 4,用AES解密数据
/// </summary>
/// <param name="encryptedSource">已加密的内容</param>
/// <param name="key">密钥</param>
public static string Decrypt(string toDecrypt)
{
if (string.IsNullOrEmpty(toDecrypt)) return "";
try
{
byte[] _key = Encoding.ASCII.GetBytes(key);
Aes aes = Aes.Create("AES");
aes.Mode = CipherMode.ECB;
aes.Padding = PaddingMode.PKCS7;
aes.Key = _key;
ICryptoTransform cTransform = aes.CreateDecryptor();
byte[] encryptedData = Convert.FromBase64String(toDecrypt);
string encryptedString = Encoding.UTF8.GetString(encryptedData);
byte[] _source = Hex_16To2(encryptedString);
byte[] originalSrouceData = cTransform.TransformFinalBlock(_source, 0, _source.Length);
return Encoding.UTF8.GetString(originalSrouceData);
}
catch (Exception)
{
return "";
}
}
/// <summary>
/// 2进制转16进制
/// </summary>
static string Hex_2To16(byte[] bytes)
{
string hexString = string.Empty;
Int32 iLength = 65535;
if (bytes != null)
{
StringBuilder strB = new StringBuilder();
if (bytes.Length < iLength)
{
iLength = bytes.Length;
}
for (int i = 0; i < iLength; i++)
{
strB.Append(bytes[i].ToString("X2"));
}
hexString = strB.ToString();
}
return hexString;
}
/// <summary>
/// 16进制转2进制
/// </summary>
static byte[] Hex_16To2(string hexString)
{
if ((hexString.Length % 2) != 0)
{
hexString += " ";
}
byte[] returnBytes = new Byte[hexString.Length / 2];
for (Int32 i = 0; i < returnBytes.Length; i++)
{
returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
}
return returnBytes;
}
#endregion
}
}
+304
View File
@@ -0,0 +1,304 @@
/******************************
* 说明:数据库连接参数配置类
* 创建人:龚宇超
* 创建日期:2017-07-24
* 修改人:
* 修改日期:
* 修改备注:
* 版本:1.0.0.0
******************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Win32;
using System.Data.SqlClient;
using System.Data;
using Lskj.Util;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Diagnostics;
using System.Windows.Forms;
using System.Data.Odbc;
namespace Lskj.Core
{
/// <summary>
/// 数据库连接参数配置类
/// </summary>
public sealed class DBConfig
{
private static string _regKey = "AA_LS_Erp V2.0";
private static DBConfig _instance = null;
/// <summary>
/// DBConfig静态单例对象
/// </summary>
/// <value>The instance.</value>
public static DBConfig Instance
{
get
{
if (_instance == null)
{
_instance = new DBConfig();
_instance.ReadConfig();
_instance.WriteConfig();
}
return _instance;
}
}
/// <summary>
/// 数据库名
/// </summary>
public string DataBase;
/// <summary>
/// 帐套
/// </summary>
public string DataBook;
/// <summary>
/// 服务器名
/// </summary>
public string ServerName;
/// <summary>
/// 登录名
/// </summary>
public string LoginName;
/// <summary>
/// 通知员工ID
/// </summary>
public string NoticeUserID;
/// <summary>
/// 通知员工姓名
/// </summary>
public string NoticeUserName;
/// <summary>
/// 系统筛选id
/// </summary>
public string ProGramme;
/// <summary>
/// 文件升级标志
/// </summary>
public bool UpdateSet;
///<summary>
///智能客户端启动
///</summary>
public bool SmallClient;
///<summary>
///智能客户端启动
///</summary>
public bool NoticeClient;
/// <summary>
/// The notice show window
/// </summary>
public bool NoticeShowWindow;
/// <summary>
/// The notice flicker
/// </summary>
public bool NoticeFlicker;
/// <summary>
/// The notice exit
/// </summary>
public bool NoticeExit;
/// <summary>
/// 内外外网标志
/// </summary>
public bool Internet;
/// <summary>
/// 是否注册过高拍仪
/// </summary>
public bool IsCmpCapture;
/// <summary>
/// 班次
/// </summary>
public string BCName;
//public string Connection1 = "QkYyNjE3QTcxQjc4RDFFMDlERjlFMDc1QkIyMDVGRjdDRUIyMEVEOUM5NjBCQjc5NTA5NzdEQTk0MkNEQTE1RTFGMEIwMThFNUJDQTE0RjE1NjQwM0U5QTYxMThCMDY2MTA4NkE2OTIxNTNBQjQ0MjRDMDIwM0Q5OEVDQjkwQTVCN0RENjJBODkxNUNGOUM5OEI5RTEzN0E3ODBERjg2OURCNEQ5QTlCMzhCQUZGQ0FBNUREMjY4M0FCODg2RTkxMDRERTQ3MjRGQTE1MERDOTJGRDFDRjY2REQ1ODYyREUzN0RGM0ZBQzc4NzJENjIwNDg4RUUyNkI3ODE1RjlDM0I0MjNCQzcyOENDN0VDMTg0QUU0MjgwMDVDMENBOUZF";
public string Connection2 = "Njk5NTI5NDE5RUI2ODM4MEQ5MEJFQkU3NzM3REQxQThDREM4NzRFNUY3QzYzMkVEOEEzODRBMzJBRjIwRUY4Njg4Qjg3M0Q1MTY3MjAxRkY2OTNGMzk3MUZBRjMxMzdDQ0U4RjMxQUVERjdBQzI5MEExNjQ3ODlDNkEwODVBMUJDMUJGN0U2RUJENkMwQzhERTFCNzgyMjg1MjBFQkE2MkU4NjMyQjBEMDY0QjQ0MzVDQ0QxMjMzQTA3NjI3QjQyOTczQUJBMUI0OUNGMkE5REYzOTI2NDFBRTY3QzFGQTJCRDFDNUIzQ0FCMzA4QzEwMjc2MTI5QjU2MzgxMjBDN0MwNUFGNUU3QTdBRTI2REQzREEyM0FFM0I2MUVGMzYw";
public string Connection3 = "NjQ0OTQzRTY1MkUwQUUxQTdCQTlBRjkwRjI4QkU1MTRDNTc5RDI0RTg5Q0Q5RjU2QjQ3RjY4REY2NEY1QjM5QUNCREIzMTBDRUMxREQ5NzlBREUxMjQ5NzdCM0Y0RUM1Qjc2MEI3MzFFNTcxQ0Q5MzA5RTI5RUFGNDQxOTMyRkQ1RTdDNjcyRTFCQjUyM0Y4RkE2NEE2N0QyNzEyQzVCRTcyOUJBRTYxMjMzRjYwMjg5NzIyRjJGOTdDMzE0NTQ0MjIwQzFBNEI4MDI0OUNFNTJDMzlEOEMwNjY1MjA3M0YyQkQ0NDRDOTg5REMxMUVCMDM1MUU0OTEzQzQwRDBDQ0E3Rjk4QjgyNzRFRjYzQzBEMDcxQzVFMjdCMTIxNkE2MzI0MEIyNDkwOERGNUFDMjRGMEYxRkFFNzJEQTIwM0EyRjU0N0U4OEFENDBEMjEzNUY1OTI5NUUxRDM1N0I0Rg==";
public string Connection4 = "NjU3MDQ0Q0JDREI0Mjc2OUY4RTBCOEIxMjBDOEM4MEQ2QUMwMjNEOUVDOTQ4NEMwRDE2RDdEMTQwNEQwODg3MURBMzRENkIxNEFENEYwQTcyMkEwMTE0NDhDM0NGNUZBQ0U4RjMxQUVERjdBQzI5MEExNjQ3ODlDNkEwODVBMUI3NDlCRkU1RDBGQUI0RUJFODlFNkE5MzlFNkIzODAyODEyRjFGQzE4NjVCMEM2OThDRDgzRUY4M0ZGNEExRkEyRUFGQzE4NTg1QkZBMEMwRTI5NzAzQzkzMzY2RUU0Mzc5RkI4NkVDRTM3NDNBMTk0ODJBQTNDNUY2RDlGMzU3MUEyOUEzOEI5RjA3NzA2NjM1NUNFM0U5RjNCNzMzM0RBMUY2MDkxQUZDQ0YxN0Q5MDgwOEY0NzZEMUM3MjQyMkRBOUY2N0NFRUE3MTkwNzk0OTA2NUYyRDJBMEM4RUU4OQ==";
public string Connection1 = "MzYwRTRBN0VDQjhEQTVERDBBNDA1RDg2N0VFRkQwMEM5QjNEMzI1OUFBMUFERUIyMTU0NTJDRTE4MDZEQzNFNzcxODdERTc0NjhFRDM5OEMyNkUwNzEzRUI0ODkwNkE1M0RBRkVFQjQzNDI2QTk1RTlCRDEyQzE3NkNFRURERDdCOTc0RUJCOUE1NTE5NDYxOEY0RUIxQUQwQzgyRjhBMw==";
/// <summary>
/// <para>说明:读取注册表配置</para>
/// <para>创建人:龚宇超</para>
/// <para>创建日期:2017-08-07 </para>
/// <para>修改人:</para>
/// <para>修改日期:</para>
/// <para>修改备注:</para>
/// <para>版本:1.0</para>
/// </summary>
public void ReadConfig()
{
RegistryKey regKey = Registry.CurrentUser;
try
{
RegistryKey erpKey = regKey.CreateSubKey("AA_LS_Erp V2.0");
erpKey.CreateSubKey("File");
}
catch (Exception)
{
}
RegistryKey subKey = regKey.OpenSubKey(_regKey);
subKey = subKey.OpenSubKey("File", true);
DataBase = subKey.GetValue("datastr", "") + "";
ServerName = subKey.GetValue("ServerName", "") + "";
LoginName = subKey.GetValue("LoginName", "") + "";
UpdateSet = subKey.GetValue("UpdateSet", "0") + "" == "1" || subKey.GetValue("UpdateSet", "0") + "" == "True" ? true : false;
SmallClient = subKey.GetValue("SmallClient", "0") + "" == "1" || subKey.GetValue("SmallClient", "0") + "" == "True" ? true : false;
NoticeClient = subKey.GetValue("NoticeClient", "0") + "" == "1" || subKey.GetValue("NoticeClient", "0") + "" == "True" ? true : false;
Internet = subKey.GetValue("Internet", "1") + "" == "0" ? true : false;
ProGramme = subKey.GetValue("ProGramme", "") + "";
NoticeUserName = subKey.GetValue("NoticeUserName", "") + "";
NoticeUserID = subKey.GetValue("NoticeUserID", "") + "";
NoticeShowWindow = subKey.GetValue("NoticeShowWindow", "0") + "" == "1" || subKey.GetValue("NoticeShowWindow", "0") + "" == "True" ? true : false;
NoticeFlicker = subKey.GetValue("NoticeFlicker", "0") + "" == "0" || subKey.GetValue("NoticeFlicker", "0") + "" == "False" ? false : true;
NoticeExit = subKey.GetValue("NoticeExit", "0") + "" == "1" || subKey.GetValue("NoticeExit", "0") + "" == "True" ? true : false;
if (subKey.GetValue("IsCmpCapture") == null)
{
subKey.SetValue("IsCmpCapture", 0);
}
IsCmpCapture = subKey.GetValue("IsCmpCapture", "0") + "" == "1" || subKey.GetValue("IsCmpCapture", "0") + "" == "True" ? true : false;
try
{
DataBook = subKey.GetValue("DataBook", "") + "";
}
catch (Exception)
{
}
}
/// <summary>
/// <para>说明:激活高拍仪控件</para>
/// <para>创建人:龚宇超</para>
/// <para>创建日期:2018-07-31 </para>
/// <para>修改人:</para>
/// <para>修改日期:</para>
/// <para>修改备注:</para>
/// <para>版本:1.0</para>
/// </summary>
public void SetActiveOcx(string subkeyName)
{
RegistryKey regKey = Registry.CurrentUser;
RegistryKey subKey = regKey.OpenSubKey(_regKey);
subKey = subKey.OpenSubKey("File", true);
subKey.SetValue(subkeyName, 1);
}
/// <summary>
/// <para>说明:写配置</para>
/// <para>创建人:龚宇超</para>
/// <para>创建日期:2017-08-07 </para>
/// <para>修改人:</para>
/// <para>修改日期:</para>
/// <para>修改备注:</para>
/// <para>版本:1.0</para>
/// </summary>
public void WriteConfig()
{
RegistryKey regKey = Registry.CurrentUser;
RegistryKey subKey = regKey.OpenSubKey(_regKey);
subKey = subKey.OpenSubKey("File", true);
subKey.SetValue("datastr", DataBase);
subKey.SetValue("ServerName", ServerName);
subKey.SetValue("LoginName", LoginName);
subKey.SetValue("UpdateSet", UpdateSet);
subKey.SetValue("SmallClient", SmallClient);
subKey.SetValue("NoticeClient", NoticeClient);
subKey.SetValue("DataBook", DataBook);
subKey.SetValue("NoticeUserID", NoticeUserID);
subKey.SetValue("ProGramme", ProGramme);
subKey.SetValue("NoticeUserName", NoticeUserName);
subKey.SetValue("NoticeShowWindow", NoticeShowWindow);
subKey.SetValue("NoticeFlicker", NoticeFlicker);
subKey.SetValue("NoticeExit", NoticeExit);
subKey.Close();
}
/// <summary>
/// <para>说明:获取C#连接字符串</para>
/// <para>创建人:龚宇超</para>
/// <para>创建日期:2017-08-07 </para>
/// <para>修改人:</para>
/// <para>修改日期:</para>
/// <para>修改备注:</para>
/// <para>版本:1.0</para>
/// </summary>
/// <returns>System.String.</returns>
public string GetConnection()
{
return string.Format(AESUtil.Decrypt(Connection1), ServerName, DataBase);
}
/// <summary>
/// <para>说明:获取delphi连接字符串</para>
/// <para>创建人:龚宇超</para>
/// <para>创建日期:2017-08-07 </para>
/// <para>修改人:</para>
/// <para>修改日期:</para>
/// <para>修改备注:</para>
/// <para>版本:1.0</para>
/// </summary>
/// <returns>System.String.</returns>
public string GetDelphiConnection()
{
return string.Format(AESUtil.Decrypt(Connection2), ServerName, DataBase);
}
/// <summary>
/// <para>说明:获取</para>
/// <para>创建人:龚宇超</para>
/// <para>创建日期:2018-03-28 </para>
/// <para>修改人:</para>
/// <para>修改日期:</para>
/// <para>修改备注:</para>
/// <para>版本:1.0</para>
/// </summary>
/// <returns>System.String.</returns>
public string GetLsCrmConnection()
{
return Internet ? AESUtil.Decrypt(Connection3) : AESUtil.Decrypt(Connection4);
}
/// <summary>
/// <para>说明:创建数据库连接</para>
/// <para>创建人:龚宇超</para>
/// <para>创建日期:2017-08-07 </para>
/// <para>修改人:</para>
/// <para>修改日期:</para>
/// <para>修改备注:</para>
/// <para>版本:1.0</para>
/// </summary>
/// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
public bool CreateConnection()
{
string connStr = GetConnection();
if (OdbcHelper._connection != null)
{
try
{
OdbcHelper._connection.Close();
OdbcHelper._connection.Dispose();
}
catch (Exception)
{
}
OdbcHelper._connection = null;
}
try
{
OdbcHelper._connection = new OdbcConnection(connStr);//因为修改了数据库属性,无法直接连接sql server,就更改了连接语句,并把SqlConnection改成OdbcHelper
OdbcHelper._connection.Open();
return true;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return false;
}
}
}
@@ -0,0 +1,546 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace Lskj.TxtFileRead
{
/// <summary>
/// 文件操作帮助类
/// </summary>
public class FileUtilHelper
{
#region
/// <summary>
/// 检测指定目录是否存在,如果存在则返回true。
/// </summary>
/// <param name="directoryPath">目录的绝对路径</param>
public static bool IsExistDirectory(string directoryPath)
{
return Directory.Exists(directoryPath);
}
#endregion
#region
/// <summary>
/// 检测指定文件是否存在,如果存在则返回true。
/// </summary>
/// <param name="filePath">文件的绝对路径</param>
public static bool IsExistFile(string filePath)
{
return File.Exists(filePath);
}
#endregion
#region
/// <summary>
/// 检测指定目录是否为空
/// </summary>
/// <param name="directoryPath">指定目录的绝对路径</param>
public static bool IsEmptyDirectory(string directoryPath)
{
try
{
//判断是否存在文件
string[] fileNames = GetFileNames(directoryPath);
if (fileNames.Length > 0)
{
return false;
}
//判断是否存在文件夹
string[] directoryNames = GetDirectories(directoryPath);
if (directoryNames.Length > 0)
{
return false;
}
return true;
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region
/// <summary>
/// 检测指定目录中是否存在指定的文件,若要搜索子目录请使用重载方法.
/// </summary>
/// <param name="directoryPath">指定目录的绝对路径</param>
/// <param name="searchPattern">模式字符串,"*"代表0或N个字符,"?"代表1个字符。
/// 范例:"Log*.xml"表示搜索所有以Log开头的Xml文件。</param>
public static bool IsContainsFile(string directoryPath, string searchPattern)
{
try
{
//获取指定的文件列表
string[] fileNames = GetFileNames(directoryPath, searchPattern, false);
//判断指定文件是否存在
if (fileNames.Length == 0)
{
return false;
}
else
{
return true;
}
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// 检测指定目录中是否存在指定的文件
/// </summary>
/// <param name="directoryPath">指定目录的绝对路径</param>
/// <param name="searchPattern">模式字符串,"*"代表0或N个字符,"?"代表1个字符。
/// 范例:"Log*.xml"表示搜索所有以Log开头的Xml文件。</param>
/// <param name="isSearchChild">是否搜索子目录</param>
public static bool IsContainsFile(string directoryPath, string searchPattern, bool isSearchChild)
{
try
{
//获取指定的文件列表
string[] fileNames = GetFileNames(directoryPath, searchPattern, true);
//判断指定文件是否存在
if (fileNames.Length == 0)
{
return false;
}
else
{
return true;
}
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region
/// <summary>
/// 创建一个目录
/// </summary>
/// <param name="directoryPath">目录的绝对路径</param>
public static void CreateDirectory(string directoryPath)
{
//如果目录不存在则创建该目录
if (!IsExistDirectory(directoryPath))
{
Directory.CreateDirectory(directoryPath);
}
}
#endregion
#region
/// <summary>
/// 创建一个文件
/// </summary>
/// <param name="filePath">文件的绝对路径</param>
public static void CreateFile(string filePath)
{
try
{
//如果文件不存在则创建该文件
if (!IsExistFile(filePath))
{
//创建一个FileInfo对象
FileInfo file = new FileInfo(filePath);
//创建文件
FileStream fs = file.Create();
//关闭文件流
fs.Close();
}
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// 创建一个文件,并将字节流写入文件。
/// </summary>
/// <param name="filePath">文件的绝对路径</param>
/// <param name="buffer">二进制流数据</param>
public static void CreateFile(string filePath, byte[] buffer)
{
try
{
//如果文件不存在则创建该文件
if (!IsExistFile(filePath))
{
//创建一个FileInfo对象
FileInfo file = new FileInfo(filePath);
//创建文件
FileStream fs = file.Create();
//写入二进制流
fs.Write(buffer, 0, buffer.Length);
//关闭文件流
fs.Close();
}
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region
/// <summary>
/// 获取文本文件的行数
/// </summary>
/// <param name="filePath">文件的绝对路径</param>
public static int GetLineCount(string filePath)
{
//将文本文件的各行读到一个字符串数组中
string[] rows = File.ReadAllLines(filePath);
//返回行数
return rows.Length;
}
#endregion
#region
/// <summary>
/// 获取一个文件的长度,单位为Byte
/// </summary>
/// <param name="filePath">文件的绝对路径</param>
public static int GetFileSize(string filePath)
{
//创建一个文件对象
FileInfo fi = new FileInfo(filePath);
//获取文件的大小
return (int)fi.Length;
}
#endregion
#region
/// <summary>
/// 获取指定目录中所有文件列表
/// </summary>
/// <param name="directoryPath">指定目录的绝对路径</param>
public static string[] GetFileNames(string directoryPath)
{
//如果目录不存在,则抛出异常
if (!IsExistDirectory(directoryPath))
{
throw new FileNotFoundException();
}
//获取文件列表
return Directory.GetFiles(directoryPath);
}
/// <summary>
/// 获取指定目录及子目录中所有文件列表
/// </summary>
/// <param name="directoryPath">指定目录的绝对路径</param>
/// <param name="searchPattern">模式字符串,"*"代表0或N个字符,"?"代表1个字符。
/// 范例:"Log*.xml"表示搜索所有以Log开头的Xml文件。</param>
/// <param name="isSearchChild">是否搜索子目录</param>
public static string[] GetFileNames(string directoryPath, string searchPattern, bool isSearchChild)
{
//如果目录不存在,则抛出异常
if (!IsExistDirectory(directoryPath))
{
throw new FileNotFoundException();
}
try
{
if (isSearchChild)
{
return Directory.GetFiles(directoryPath, searchPattern, SearchOption.AllDirectories);
}
else
{
return Directory.GetFiles(directoryPath, searchPattern, SearchOption.TopDirectoryOnly);
}
}
catch (IOException ex)
{
throw ex;
}
}
#endregion
#region
/// <summary>
/// 获取指定目录中所有子目录列表,若要搜索嵌套的子目录列表,请使用重载方法.
/// </summary>
/// <param name="directoryPath">指定目录的绝对路径</param>
public static string[] GetDirectories(string directoryPath)
{
try
{
return Directory.GetDirectories(directoryPath);
}
catch (IOException ex)
{
throw ex;
}
}
/// <summary>
/// 获取指定目录及子目录中所有子目录列表
/// </summary>
/// <param name="directoryPath">指定目录的绝对路径</param>
/// <param name="searchPattern">模式字符串,"*"代表0或N个字符,"?"代表1个字符。
/// 范例:"Log*.xml"表示搜索所有以Log开头的Xml文件。</param>
/// <param name="isSearchChild">是否搜索子目录</param>
public static string[] GetDirectories(string directoryPath, string searchPattern, bool isSearchChild)
{
try
{
if (isSearchChild)
{
return Directory.GetDirectories(directoryPath, searchPattern, SearchOption.AllDirectories);
}
else
{
return Directory.GetDirectories(directoryPath, searchPattern, SearchOption.TopDirectoryOnly);
}
}
catch (IOException ex)
{
throw ex;
}
}
#endregion
#region
/// <summary>
/// 向文本文件中写入内容
/// </summary>
/// <param name="filePath">文件的绝对路径</param>
/// <param name="content">写入的内容</param>
public static void WriteText(string filePath, string content)
{
//向文件写入内容
File.WriteAllText(filePath, content);
}
#endregion
#region
/// <summary>
/// 向文本文件的尾部追加内容
/// </summary>
/// <param name="filePath">文件的绝对路径</param>
/// <param name="content">写入的内容</param>
public static void AppendText(string filePath, string content)
{
File.AppendAllText(filePath, content);
}
#endregion
#region
/// <summary>
/// 将源文件的内容复制到目标文件中
/// </summary>
/// <param name="sourceFilePath">源文件的绝对路径</param>
/// <param name="destFilePath">目标文件的绝对路径</param>
public static void Copy(string sourceFilePath, string destFilePath)
{
File.Copy(sourceFilePath, destFilePath, true);
}
#endregion
#region
/// <summary>
/// 将文件移动到指定目录
/// </summary>
/// <param name="sourceFilePath">需要移动的源文件的绝对路径</param>
/// <param name="descDirectoryPath">移动到的目录的绝对路径</param>
public static bool Move(string sourceFilePath, string descDirectoryPath)
{
//获取源文件的名称
string sourceFileName = GetFileName(sourceFilePath);
if (IsExistDirectory(descDirectoryPath))
{
//如果目标中存在同名文件,则删除
if (IsExistFile(descDirectoryPath + "\\" + sourceFileName))
{
DeleteFile(descDirectoryPath + "\\" + sourceFileName);
}
//将文件移动到指定目录
File.Move(sourceFilePath, descDirectoryPath + "\\" + sourceFileName);
return true;
}
return false;
}
#endregion
#region ( )
/// <summary>
/// 从文件的绝对路径中获取文件名( 包含扩展名 )
/// </summary>
/// <param name="filePath">文件的绝对路径</param>
public static string GetFileName(string filePath)
{
//获取文件的名称
FileInfo fi = new FileInfo(filePath);
return fi.Name;
}
#endregion
#region ( )
/// <summary>
/// 从文件的绝对路径中获取文件名( 不包含扩展名 )
/// </summary>
/// <param name="filePath">文件的绝对路径</param>
public static string GetFileNameNoExtension(string filePath)
{
//获取文件的名称
FileInfo fi = new FileInfo(filePath);
return fi.Name.Split('.')[0];
}
#endregion
#region
/// <summary>
/// 从文件的绝对路径中获取扩展名
/// </summary>
/// <param name="filePath">文件的绝对路径</param>
public static string GetExtension(string filePath)
{
//获取文件的名称
FileInfo fi = new FileInfo(filePath);
return fi.Extension;
}
#endregion
#region
/// <summary>
/// 将文件读取到缓冲区中
/// </summary>
/// <param name="filePath">文件的绝对路径</param>
public static byte[] FileToBytes(string filePath)
{
//获取文件的大小
int fileSize = GetFileSize(filePath);
//创建一个临时缓冲区
byte[] buffer = new byte[fileSize];
//创建一个文件流
FileInfo fi = new FileInfo(filePath);
FileStream fs = fi.Open(FileMode.Open);
try
{
//将文件流读入缓冲区
fs.Read(buffer, 0, fileSize);
return buffer;
}
catch (IOException ex)
{
throw ex;
}
finally
{
//关闭文件流
fs.Close();
}
}
#endregion
#region
/// <summary>
/// 将文件读取到字符串中
/// </summary>
/// <param name="filePath">文件的绝对路径</param>
/// <param name="encoding">字符编码</param>
public static string FileToString(string filePath, Encoding encoding)
{
//创建流读取器
StreamReader reader = new StreamReader(filePath, encoding);
try
{
//读取流
return reader.ReadToEnd();
}
catch (Exception ex)
{
throw ex;
}
finally
{
//关闭流读取器
reader.Close();
}
}
#endregion
#region
/// <summary>
/// 清空指定目录下所有文件及子目录,但该目录依然保存.
/// </summary>
/// <param name="directoryPath">指定目录的绝对路径</param>
public static void ClearDirectory(string directoryPath)
{
if (IsExistDirectory(directoryPath))
{
//删除目录中所有的文件
string[] fileNames = GetFileNames(directoryPath);
for (int i = 0; i < fileNames.Length; i++)
{
DeleteFile(fileNames[i]);
}
//删除目录中所有的子目录
string[] directoryNames = GetDirectories(directoryPath);
for (int i = 0; i < directoryNames.Length; i++)
{
DeleteDirectory(directoryNames[i]);
}
}
}
#endregion
#region
/// <summary>
/// 清空文件内容
/// </summary>
/// <param name="filePath">文件的绝对路径</param>
public static void ClearFile(string filePath)
{
//删除文件
File.Delete(filePath);
//重新创建该文件
CreateFile(filePath);
}
#endregion
#region
/// <summary>
/// 删除指定文件
/// </summary>
/// <param name="filePath">文件的绝对路径</param>
public static void DeleteFile(string filePath)
{
if (IsExistFile(filePath))
{
File.Delete(filePath);
}
}
#endregion
#region
/// <summary>
/// 删除指定目录及其所有子目录
/// </summary>
/// <param name="directoryPath">指定目录的绝对路径</param>
public static void DeleteDirectory(string directoryPath)
{
if (IsExistDirectory(directoryPath))
{
Directory.Delete(directoryPath, true);
}
}
#endregion
#region (B)(M)
/// <summary>
/// 将字节(B)转换成兆(M),并保留两位小数
/// </summary>
public static string ConvertByteToMB(int byteLength)
{
return Math.Round((double)byteLength / (1024 * 1024), 2).ToString() + "M";
}
#endregion
#region
public static string ReplaceBadCharOfFileName(string fileName)
{
fileName = fileName.Replace("\\", string.Empty);
fileName = fileName.Replace("/", string.Empty);
fileName = fileName.Replace(":", string.Empty);
fileName = fileName.Replace("*", string.Empty);
fileName = fileName.Replace("?", string.Empty);
fileName = fileName.Replace("\"", string.Empty);
fileName = fileName.Replace("<", string.Empty);
fileName = fileName.Replace(">", string.Empty);
fileName = fileName.Replace("|", string.Empty);
fileName = fileName.Replace(" ", string.Empty);
return fileName.ToString();
}
#endregion
}
}
+275
View File
@@ -0,0 +1,275 @@
using System.Windows.Forms;
namespace Lskj.TxtFileRead
{
partial class FrmMain
{
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
/// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows
/// <summary>
/// 设计器支持所需的方法 - 不要
/// 使用代码编辑器修改此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.panelControl1 = new DevExpress.XtraEditors.PanelControl();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.txtServerName = new DevExpress.XtraEditors.TextEdit();
this.labelControl4 = new DevExpress.XtraEditors.LabelControl();
this.txtDataBase = new DevExpress.XtraEditors.TextEdit();
this.labelControl3 = new DevExpress.XtraEditors.LabelControl();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.txt_ftpAddress = new DevExpress.XtraEditors.TextEdit();
this.lab_ftp = new DevExpress.XtraEditors.LabelControl();
this.labelControl1 = new DevExpress.XtraEditors.LabelControl();
this.txtPassword = new DevExpress.XtraEditors.TextEdit();
this.txt_Username = new DevExpress.XtraEditors.TextEdit();
this.labelControl2 = new DevExpress.XtraEditors.LabelControl();
this.btnSave = new DevExpress.XtraEditors.SimpleButton();
this.panelControl2 = new DevExpress.XtraEditors.PanelControl();
this.show_txt = new DevExpress.XtraEditors.MemoEdit();
((System.ComponentModel.ISupportInitialize)(this.panelControl1)).BeginInit();
this.panelControl1.SuspendLayout();
this.groupBox2.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.txtServerName.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.txtDataBase.Properties)).BeginInit();
this.groupBox1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.txt_ftpAddress.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.txtPassword.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.txt_Username.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.panelControl2)).BeginInit();
this.panelControl2.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.show_txt.Properties)).BeginInit();
this.SuspendLayout();
//
// panelControl1
//
this.panelControl1.AutoSize = true;
this.panelControl1.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.panelControl1.BorderStyle = DevExpress.XtraEditors.Controls.BorderStyles.NoBorder;
this.panelControl1.Controls.Add(this.groupBox2);
this.panelControl1.Controls.Add(this.groupBox1);
this.panelControl1.Controls.Add(this.btnSave);
this.panelControl1.Dock = System.Windows.Forms.DockStyle.Top;
this.panelControl1.Location = new System.Drawing.Point(0, 0);
this.panelControl1.Name = "panelControl1";
this.panelControl1.Size = new System.Drawing.Size(811, 113);
this.panelControl1.TabIndex = 0;
//
// groupBox2
//
this.groupBox2.Controls.Add(this.txtServerName);
this.groupBox2.Controls.Add(this.labelControl4);
this.groupBox2.Controls.Add(this.txtDataBase);
this.groupBox2.Controls.Add(this.labelControl3);
this.groupBox2.Font = new System.Drawing.Font("微软雅黑", 10F);
this.groupBox2.Location = new System.Drawing.Point(389, 9);
this.groupBox2.Name = "groupBox2";
this.groupBox2.Size = new System.Drawing.Size(285, 101);
this.groupBox2.TabIndex = 12;
this.groupBox2.TabStop = false;
this.groupBox2.Text = "服务器信息";
//
// txtServerName
//
this.txtServerName.Location = new System.Drawing.Point(114, 30);
this.txtServerName.Name = "txtServerName";
this.txtServerName.Properties.Appearance.Font = new System.Drawing.Font("Tahoma", 10F);
this.txtServerName.Properties.Appearance.Options.UseFont = true;
this.txtServerName.Size = new System.Drawing.Size(135, 22);
this.txtServerName.TabIndex = 12;
//
// labelControl4
//
this.labelControl4.Appearance.Font = new System.Drawing.Font("微软雅黑", 10F);
this.labelControl4.Location = new System.Drawing.Point(31, 32);
this.labelControl4.Name = "labelControl4";
this.labelControl4.Size = new System.Drawing.Size(84, 20);
this.labelControl4.TabIndex = 11;
this.labelControl4.Text = "服务器地址:";
//
// txtDataBase
//
this.txtDataBase.Location = new System.Drawing.Point(114, 64);
this.txtDataBase.Name = "txtDataBase";
this.txtDataBase.Properties.Appearance.Font = new System.Drawing.Font("Tahoma", 10F);
this.txtDataBase.Properties.Appearance.Options.UseFont = true;
this.txtDataBase.Size = new System.Drawing.Size(135, 22);
this.txtDataBase.TabIndex = 10;
//
// labelControl3
//
this.labelControl3.Appearance.Font = new System.Drawing.Font("微软雅黑", 10F);
this.labelControl3.Location = new System.Drawing.Point(31, 66);
this.labelControl3.Name = "labelControl3";
this.labelControl3.Size = new System.Drawing.Size(82, 20);
this.labelControl3.TabIndex = 9;
this.labelControl3.Text = "数 据 库 名:";
//
// groupBox1
//
this.groupBox1.Controls.Add(this.txt_ftpAddress);
this.groupBox1.Controls.Add(this.lab_ftp);
this.groupBox1.Controls.Add(this.labelControl1);
this.groupBox1.Controls.Add(this.txtPassword);
this.groupBox1.Controls.Add(this.txt_Username);
this.groupBox1.Controls.Add(this.labelControl2);
this.groupBox1.Font = new System.Drawing.Font("微软雅黑", 10F);
this.groupBox1.Location = new System.Drawing.Point(12, 9);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(371, 101);
this.groupBox1.TabIndex = 11;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "基本信息";
//
// txt_ftpAddress
//
this.txt_ftpAddress.Location = new System.Drawing.Point(92, 30);
this.txt_ftpAddress.Name = "txt_ftpAddress";
this.txt_ftpAddress.Properties.Appearance.Font = new System.Drawing.Font("Tahoma", 10F);
this.txt_ftpAddress.Properties.Appearance.Options.UseFont = true;
this.txt_ftpAddress.Size = new System.Drawing.Size(218, 22);
this.txt_ftpAddress.TabIndex = 3;
//
// lab_ftp
//
this.lab_ftp.Appearance.Font = new System.Drawing.Font("微软雅黑", 10F);
this.lab_ftp.Location = new System.Drawing.Point(26, 32);
this.lab_ftp.Name = "lab_ftp";
this.lab_ftp.Size = new System.Drawing.Size(63, 20);
this.lab_ftp.TabIndex = 2;
this.lab_ftp.Text = "Ftp地址:";
//
// labelControl1
//
this.labelControl1.Appearance.Font = new System.Drawing.Font("微软雅黑", 10F);
this.labelControl1.Location = new System.Drawing.Point(26, 66);
this.labelControl1.Name = "labelControl1";
this.labelControl1.Size = new System.Drawing.Size(64, 20);
this.labelControl1.TabIndex = 5;
this.labelControl1.Text = "用 户 名:";
//
// txtPassword
//
this.txtPassword.Location = new System.Drawing.Point(234, 66);
this.txtPassword.Name = "txtPassword";
this.txtPassword.Properties.Appearance.Font = new System.Drawing.Font("Tahoma", 10F);
this.txtPassword.Properties.Appearance.Options.UseFont = true;
this.txtPassword.Properties.PasswordChar = '*';
this.txtPassword.Size = new System.Drawing.Size(76, 22);
this.txtPassword.TabIndex = 8;
//
// txt_Username
//
this.txt_Username.Location = new System.Drawing.Point(92, 66);
this.txt_Username.Name = "txt_Username";
this.txt_Username.Properties.Appearance.Font = new System.Drawing.Font("Tahoma", 10F);
this.txt_Username.Properties.Appearance.Options.UseFont = true;
this.txt_Username.Size = new System.Drawing.Size(81, 22);
this.txt_Username.TabIndex = 6;
//
// labelControl2
//
this.labelControl2.Appearance.Font = new System.Drawing.Font("微软雅黑", 10F);
this.labelControl2.Location = new System.Drawing.Point(177, 66);
this.labelControl2.Name = "labelControl2";
this.labelControl2.Size = new System.Drawing.Size(54, 20);
this.labelControl2.TabIndex = 7;
this.labelControl2.Text = "密 码:";
//
// btnSave
//
this.btnSave.Location = new System.Drawing.Point(708, 42);
this.btnSave.Name = "btnSave";
this.btnSave.Size = new System.Drawing.Size(79, 29);
this.btnSave.TabIndex = 1;
this.btnSave.Text = "执行";
this.btnSave.Click += new System.EventHandler(this.OnSaveClick);
//
// panelControl2
//
this.panelControl2.BorderStyle = DevExpress.XtraEditors.Controls.BorderStyles.NoBorder;
this.panelControl2.Controls.Add(this.show_txt);
this.panelControl2.Dock = System.Windows.Forms.DockStyle.Fill;
this.panelControl2.Location = new System.Drawing.Point(0, 113);
this.panelControl2.Name = "panelControl2";
this.panelControl2.Size = new System.Drawing.Size(811, 403);
this.panelControl2.TabIndex = 1;
//
// show_txt
//
this.show_txt.Dock = System.Windows.Forms.DockStyle.Fill;
this.show_txt.EditValue = "";
this.show_txt.Location = new System.Drawing.Point(0, 0);
this.show_txt.Name = "show_txt";
this.show_txt.Properties.Appearance.Font = new System.Drawing.Font("微软雅黑", 12F);
this.show_txt.Properties.Appearance.Options.UseFont = true;
this.show_txt.Size = new System.Drawing.Size(811, 403);
this.show_txt.TabIndex = 0;
//
// FrmMain
//
this.BackColor = System.Drawing.SystemColors.Control;
this.ClientSize = new System.Drawing.Size(811, 516);
this.Controls.Add(this.panelControl2);
this.Controls.Add(this.panelControl1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.Name = "FrmMain";
this.Text = "Ftp文件导入";
((System.ComponentModel.ISupportInitialize)(this.panelControl1)).EndInit();
this.panelControl1.ResumeLayout(false);
this.groupBox2.ResumeLayout(false);
this.groupBox2.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.txtServerName.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.txtDataBase.Properties)).EndInit();
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.txt_ftpAddress.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.txtPassword.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.txt_Username.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.panelControl2)).EndInit();
this.panelControl2.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.show_txt.Properties)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private DevExpress.XtraEditors.PanelControl panelControl1;
private DevExpress.XtraEditors.PanelControl panelControl2;
private DevExpress.XtraEditors.SimpleButton btnSave;
private DevExpress.XtraEditors.TextEdit txt_ftpAddress;
private DevExpress.XtraEditors.LabelControl lab_ftp;
private DevExpress.XtraEditors.MemoEdit show_txt;
private DevExpress.XtraEditors.TextEdit txtPassword;
private DevExpress.XtraEditors.LabelControl labelControl2;
private DevExpress.XtraEditors.TextEdit txt_Username;
private DevExpress.XtraEditors.LabelControl labelControl1;
private DevExpress.XtraEditors.TextEdit txtDataBase;
private DevExpress.XtraEditors.LabelControl labelControl3;
private GroupBox groupBox2;
private DevExpress.XtraEditors.TextEdit txtServerName;
private DevExpress.XtraEditors.LabelControl labelControl4;
private GroupBox groupBox1;
}
}
+933
View File
@@ -0,0 +1,933 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using Lskj.Core;
using System.Threading;
using Microsoft.Win32;
using System.Collections;
using System.Text.RegularExpressions;
namespace Lskj.TxtFileRead
{
public partial class FrmMain : Form
{
/// <summary>
/// ftp地址
/// </summary>
private string ftpPath;
/// <summary>
/// ftp用户名
/// </summary>
private string ftpUsername;
/// <summary>
/// ftp密码
/// </summary>
private string ftpPassword;
/// <summary>
/// ftp类
/// </summary>
private FtpHelper ftpHelper;
/// <summary>
/// 设定时间
/// </summary>
private string setTime;
/// <summary>
/// 设定时间集合
/// </summary>
private List<string> setTimes = new List<string>();
/// <summary>
///复制时间集合
/// </summary>
private List<string> ReplicationSetTimes = new List<string>();
/// <summary>
/// 下载存放路径
/// </summary>
private static string downloadPath = PubUtil.AbsolutelyPath + "ftpFiles\\";
/// <summary>
/// 移动存放路径
/// </summary>
private static string movePath = PubUtil.AbsolutelyPath + "MoveFiles\\";
/// <summary>
/// 数据库名
/// </summary>
private string dataBase = string.Empty;
/// <summary>
/// 服务器地址
/// </summary>
private string serverName = string.Empty;
/// <summary>
/// 设置配置信息文件
/// </summary>
private string iniFile = "ftpConfig.ini";
/// <summary>
/// 配置前缀
/// </summary>
private string ftpPrefix = string.Empty;
/// <summary>
/// 配置前缀集合
/// </summary>
private List<string> ftpPrefixs = new List<string>();
/// <summary>
/// 配置前缀和对应sql
/// </summary>
private Dictionary<string, string> prefixAndSql = new Dictionary<string, string>();
/// <summary>
///每个时间对应每条sqll(默认为每个时间执行所有sql)
/// </summary>
private bool SpecialExecution = false;
/// <summary>
/// 文件名存放位置
/// </summary>
private string txtFilePath = PubUtil.AbsolutelyPath + "fileName.txt";
private DateTime NowDay;//当前日期
private string fileNames;
List<string> delfileNames = new List<string>();
private System.Timers.Timer timer = new System.Timers.Timer();
private System.Timers.Timer timer1 = new System.Timers.Timer();
/// <summary>
/// 当天是否执行判断
/// </summary>
private bool isFinish = false;
bool flag = false;
//private static string _regKey = "AA_LS_Erp V2.0";
/// <summary>
/// 是否启动
/// </summary>
private bool activate = false;
public FrmMain()
{
InitializeComponent();
}
/// <summary>
/// <para>说明:初始化</para>
/// <para>创建人:钱雄</para>
/// <para>创建日期:2020-11-07 </para>
/// <para>修改人:</para>
/// <para>修改日期:</para>
/// <para>修改备注:</para>
/// <para>版本:1.0</para>
/// </summary>
/// <param name="item">The item.</param>
protected override void OnLoad(EventArgs e)
{
//this.timeEdit1.Format = DateTimePickerFormat.Custom;
//this.timeEdit1.CustomFormat = "HH:mm:ss";
//IniHelper.Write(iniFile, "time", "07:00:00");
try
{
setTimes = IniHelper.Read(iniFile, "time").Split(';').ToList();
ReplicationSetTimes = IniHelper.Read(iniFile, "time").Split(';').ToList();
SpecialExecution = IniHelper.Read(iniFile, "SpecialExecution").Equals("1");
ftpPath = this.txt_ftpAddress.Text = IniHelper.Read(iniFile, "ftpAddress");
ftpUsername = this.txt_Username.Text = IniHelper.Read(iniFile, "username");
ftpPassword = this.txtPassword.Text = IniHelper.Read(iniFile, "password");
dataBase = this.txtDataBase.Text = IniHelper.Read(iniFile, "dataBase");
serverName = this.txtServerName.Text = IniHelper.Read(iniFile, "serverName");
fileNames = IniHelper.Read(iniFile, "fileName").ToString();
ftpPrefix = string.IsNullOrWhiteSpace(IniHelper.Read(iniFile, "ftpPrefix").ToString()) ? "BOSS2ZSCG" : IniHelper.Read(iniFile, "ftpPrefix");//boss2zscg boss3zscg
//ftpPrefix = "BOSS2GZSCM_DEVNO_REASON_/insert BOSS_REASON_TAB(txtname,txtdate,a,b,c,d,e,f,g)values('{txtname}','{txtdate}','{0}','{1}','{2}','{3}','{4}','{5}','{6}');BOSS2GZSCM_DEVNO_TASKSEND_/insert BOSS_TASKSEND_TAB(txtname,txtdate,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o)values('{txtname}','{txtdate}','{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}','{14}');BOSS2GZCG_FIT_/insert BOSS2ZSCG_FIT(txtname,datetime,a,b,c,d,e,f,g,h,i,j,k,l)values('{txtname}','{txtdate}','{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}');BOSS2GZCG_DEVNO_/insert BOSS2ZSCG_DEVNO(txtname,datetime,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q)values('{txtname}','{txtdate}','{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}','{14}','{15}','{16}')";
//ftpPrefix = "BOSS2GZSCM_DEVNO_RESTASK_/insert BOSS_RESTASK_TAB(txtname,txtdate,a,b,c,d,e,f,g,h)values('{txtname}','{txtdate}','{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}');BOSS2GZSCM_DEVNO_REASON_/insert BOSS_REASON_TAB(txtname,txtdate,a,b,c,d,e,f,g)values('{txtname}','{txtdate}','{0}','{1}','{2}','{3}','{4}','{5}','{6}');BOSS2GZSCM_DEVNO_TASKSEND_/insert BOSS_TASKSEND_TAB(txtname,txtdate,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o)values('{txtname}','{txtdate}','{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}','{14}');BOSS2GZSCM_DEVNOREPLACE_/insert BOSS_DEVNOREPLACE_TAB(txtname,txtdate,a,b,c,d,e,f,g)values('{txtname}','{txtdate}','{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}');BOSS2GZCG_FIT_/insert BOSS2ZSCG_FIT(txtname,datetime,a,b,c,d,e,f,g,h,i,j,k,l)values('{txtname}','{txtdate}','{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}');BOSS2GZCG_DEVNO_/insert BOSS2ZSCG_DEVNO(txtname,datetime,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q)values('{txtname}','{txtdate}','{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}','{14}','{15}','{16}')";
//IniHelper.Write(iniFile, "ftpPrefix", ftpPrefix);
string txtPrefix = string.Empty;
string tableName = string.Empty;
foreach (string field in ftpPrefix.Split(';'))
{
if (!string.IsNullOrWhiteSpace(field))
{
txtPrefix = field.Split('/')[0];
tableName = field.Split('/')[1];
ftpPrefixs.Add(txtPrefix);
prefixAndSql.Add(txtPrefix, tableName);
}
}
}
catch (Exception ex)
{
RefreshLog("文件配置错误\r\n");
}
//ftpPrefix = "BOSS2GZSCM_DEVNO_RESTASK_";
//start();
//InsertData(downloadPath + "\\BOSS2GZSCM_DEVNO_RESTASK_20240302.txt");
//InsertData(downloadPath + "\\BOSS2GZSCM_DEVNO_TASKSEND_20230922.txt");
DBConfig.Instance.DataBase = dataBase;
DBConfig.Instance.ServerName = serverName;
if (!File.Exists(txtFilePath))
{
FileStream fs = new FileStream(txtFilePath, FileMode.Create, FileAccess.Write);
//不存在就新建一个文本文件
StreamWriter sw = new StreamWriter(fs);
sw.Flush();
sw.Close();
fs.Close();
}
//List<string> lines = new List<string>(File.ReadAllLines(txtFilePath).Where(s => !string.IsNullOrEmpty(s)).ToArray());
////当txt文件内容超过30行,删除第一行内容
//if (lines.Count > 30)
// lines.RemoveRange(0, prefixAndSql.Count);//删除当前配置的sql条数
//File.WriteAllLines(txtFilePath, lines.ToArray());
//InitTimer();//2023-10-11改成循环,不使用计时器
}
/// <summary>
/// 初始化时间设置
/// </summary>
private void InitTimer()
{
NowDay = DateTime.Today;
//设置timer
timer.Interval = 2000;
//设置是否重复计时,如果该属性设为False,则只执行timer_Elapsed方法一次。
timer.AutoReset = true;
timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
timer1.Interval = 2000;
timer1.AutoReset = true;
timer1.Elapsed += new System.Timers.ElapsedEventHandler(timer1_Elapsed);
}
/// <summary>
/// 配置了多个时间,对应时间执行对应sql
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
if (NowDay < DateTime.Today)
{
NowDay = DateTime.Today;
isFinish = false;
}
for (int i = 0; i < setTimes.Count; i++)
{
string setTime2 = setTimes[i].Substring(0, 5);
if (ftpPrefixs.Count >= i + 1)
{
ftpPrefix = ftpPrefixs[i];//时间对应的ftpPrefix
}
else
{
return;
}
int interception = setTime2.IndexOf('0');
if (interception == 0)//如果第一个数为0,则删除第一个数,因为DateTime.Now.ToShortTimeString().ToString()不会出现0700的情况
{
setTime2 = setTime2.Substring(1, setTime2.Length - 1);
}
if (setTime2 == DateTime.Now.ToShortTimeString().ToString() && !isFinish)
{
isFinish = true;
start();
string sqlValue = IniHelper.Read(iniFile, "sqlValue");
if (!string.IsNullOrEmpty(sqlValue) && DBConfig.Instance.CreateConnection())
{
try
{
RefreshLog(DateTime.Now + ":" + "正在执行sql\r\n");
OdbcHelper.ExecuteNonQuery(sqlValue);
RefreshLog(DateTime.Now + ":" + "SQL语句执行成功。\r\n");
}
catch (Exception ex)
{
RefreshLog(DateTime.Now + ":" + "SQL语句执行失败" + ex.Message + "\r\n");
}
}
}
//timer1.Enabled = true;
//timer1.Interval = Interval;
}
}
/// <summary>
/// 配置了单个时间,到了时间后执行所有配置sql
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
timer1.Enabled = false;
start();
string sqlValue = IniHelper.Read(iniFile, "sqlValue");
if (!string.IsNullOrEmpty(sqlValue) && DBConfig.Instance.CreateConnection())
{
try
{
OdbcHelper.ExecuteNonQuery(sqlValue);
RefreshLog(DateTime.Now + ":" + "SQL语句执行成功。\r\n");
}
catch (Exception ex)
{
RefreshLog(DateTime.Now + ":" + "SQL语句执行失败" + ex.Message + "\r\n");
}
}
}
/// <summary>
/// 到配置时间后执行所有配置sql(新版)
/// </summary>
private void Synchronous()
{
Thread thread = new Thread(() =>
{
while (true)
{
try
{
if (NowDay < DateTime.Today)
{
ReplicationSetTimes = IniHelper.Read(iniFile, "time").Split(';').ToList();
NowDay = DateTime.Today;
}
int index = 0;
for (int i = 0; i < ReplicationSetTimes.Count; i++)
{
string Time = ReplicationSetTimes[i];// Substring(0, 5);
if (string.IsNullOrWhiteSpace(Time)) continue;
int interception = Time.IndexOf('0');
if (interception == 0)//如果第一个数为0,则删除第一个数,因为DateTime.Now.ToShortTimeString().ToString()不会出现0700的情况
{
Time = Time.Substring(1, Time.Length - 1);
}
DateTime CurrentTime = DateTime.Now;//当前时间
DateTime dateTime;
DateTime.TryParse(Time, out dateTime);
if (dateTime < CurrentTime)//当前时间大于配置时间就执行
{
foreach (string item in ftpPrefixs)
{
RefreshLog(Time + " : " + item + "\r\n");
ftpPrefix = item;
start();
}
string sqlValue = IniHelper.Read(iniFile, "sqlValue");
if (!string.IsNullOrEmpty(sqlValue))
{
try
{
RefreshLog(DateTime.Now + ":" + "正在执行ini配置SQL\r\n");
OdbcHelper.ExecuteNonQuery(sqlValue);
RefreshLog(DateTime.Now + ":" + "SQL语句执行成功。\r\n");
}
catch (Exception ex)
{
RefreshLog(DateTime.Now + ":" + "SQL语句执行失败" + ex.Message + "\r\n");
}
}
RefreshLog(DateTime.Now + ":" + "执行完成\r\n");
index = i;
ReplicationSetTimes.RemoveAt(index);//临时时间记录里删除对应记录
break;
}
}
}
catch (Exception ex)
{
RefreshLog(DateTime.Now + ":" + "计时器循环错误" + ex.Message + "\r\n");
}
finally
{
Thread.Sleep(60000);
}
}
});
thread.IsBackground = true;
thread.Start();
}
/// <summary>
/// <para>说明:保存ftp地址,下载文件</para>
/// <para>创建人:钱雄</para>
/// <para>创建日期:2020-11-04 </para>
/// <para>修改人:</para>
/// <para>修改日期:</para>
/// <para>修改备注:</para>
/// <para>版本:1.0</para>
/// </summary>
/// <param name="item">The item.</param>
private void OnSaveClick(object sender, EventArgs e)
{
ftpPath = this.txt_ftpAddress.Text;
ftpUsername = this.txt_Username.Text;
ftpPassword = this.txtPassword.Text;
//setTime = setTimes.Length > 1 ? this.timeEdit1.Text + ";" + this.timeEdit2 : this.timeEdit1.Text;
dataBase = this.txtDataBase.Text;
serverName = this.txtServerName.Text;
//Interval = Convert.ToInt32(this.txtInterval.Text) * 60 * 1000;
if (string.IsNullOrEmpty(ftpPath))
{
MessageBox.Show("ftp地址不能为空!");
this.txt_ftpAddress.Focus();
}
if (string.IsNullOrEmpty(ftpUsername))
{
MessageBox.Show("用户名不能为空!");
this.txt_Username.Focus();
}
if (string.IsNullOrEmpty(ftpPassword))
{
MessageBox.Show("密码不能为空!");
this.txtPassword.Focus();
}
if (string.IsNullOrEmpty(dataBase))
{
MessageBox.Show("数据库不能为空!");
this.txtDataBase.Focus();
}
if (string.IsNullOrEmpty(serverName))
{
MessageBox.Show("服务器地址不能为空!");
this.txtServerName.Focus();
}
if (!string.IsNullOrEmpty(ftpPath) && !string.IsNullOrEmpty(ftpUsername) && !string.IsNullOrEmpty(ftpPassword) && !string.IsNullOrEmpty(dataBase) && !string.IsNullOrEmpty(serverName))
{
//IniHelper.Write(iniFile, "time", setTime);
IniHelper.Write(iniFile, "ftpAddress", ftpPath);
IniHelper.Write(iniFile, "username", ftpUsername);
IniHelper.Write(iniFile, "password", ftpPassword);
IniHelper.Write(iniFile, "serverName", serverName);
IniHelper.Write(iniFile, "dataBase", dataBase);
//设置数据库名和服务器地址
//RegistryKey regKey = Registry.CurrentUser;
//RegistryKey subKey = regKey.OpenSubKey(_regKey);
//subKey = subKey.OpenSubKey("File", true);
//subKey.SetValue("datastr", dataBase);
//subKey.SetValue("ServerName", serverName);
DBConfig.Instance.DataBase = dataBase;
DBConfig.Instance.ServerName = serverName;
show_txt.Text = "";
if (DBConfig.Instance.CreateConnection())
{
if (!activate)
{
activate = true;
RefreshLog(DateTime.Now + ":启动中,请稍后\r\n");
Synchronous();
}
else
{
RefreshLog(DateTime.Now + ":已经启动\r\n");
}
}
else
{
RefreshLog(DateTime.Now + ":数据库连接失败\r\n");
}
}
}
/// <summary>
/// 显示信息设置
/// </summary>
/// <param name="msg"></param>
public void RefreshLog(string msg)
{
Invoke((EventHandler)delegate
{
show_txt.Text += msg;
show_txt.ScrollToCaret();
});
}
/// <summary>
/// <para>说明:下载文件插入到数据库</para>
/// <para>创建人:钱雄</para>
/// <para>创建日期:2020-11-04 </para>
/// <para>修改人:</para>
/// <para>修改日期:</para>
/// <para>修改备注:</para>
/// <para>版本:1.0</para>
/// </summary>
/// <param name="item">The item.</param>
public void start()
{
delfileNames.Clear();
flag = false;
try
{
ftpHelper = new FtpHelper(ftpPath, "", ftpUsername, ftpPassword);
//测试时不下载
//if (false)
//{
List<string> lists = ftpHelper.GetAllList();
if (lists.Count == 0)
{
RefreshLog(DateTime.Now + ":ftp上没有文件需要下载\r\n");
}
else
{
RefreshLog(DateTime.Now + ":获取到" + lists.Count + "个文件\r\n");
}
for (int i = 0; i < lists.Count; i++)
{
if (lists[i].Contains(ftpPrefix))
{
//文件下载
if (!Directory.Exists(@downloadPath))
{
RefreshLog(DateTime.Now + ":" + @downloadPath + "文件夹不存在,正在创建\r\n");
Directory.CreateDirectory(@downloadPath);//不存在就创建目录
}
if (File.Exists(@downloadPath + lists[i]))
{
RefreshLog(DateTime.Now + ":" + lists[i] + "文件已存在\r\n");
//list.Add(lists[i]);
delfileNames.Add(lists[i]);
}
else
{
RefreshLog(DateTime.Now + ":" + lists[i] + "文件下载中\r\n");
if (ftpHelper.FtpDownload(lists[i].ToString(), @downloadPath + lists[i], true))
RefreshLog(DateTime.Now + ":" + lists[i].Substring(lists[i].LastIndexOf('\\') + 1) + "文件成功下载到" + downloadPath + "\r\n");
delfileNames.Add(lists[i]);
}
}
}
// }
if (!FileUtilHelper.IsEmptyDirectory(downloadPath))
{
string[] filesPath = ftpHelper.GetFiles(new DirectoryInfo(downloadPath), "*.txt");
int importCount = 0;
for (int b = 0; b < filesPath.Length; b++)
{
string filename;
string[] txtValue = File.ReadAllLines(txtFilePath).Where(s => !string.IsNullOrEmpty(s)).ToArray();
//判断txt文件中保存的文件名是否已经导入过,没有导入的则导入进去
bool exists = ((IList)txtValue).Contains(filesPath[b].Substring(filesPath[b].LastIndexOf('\\') + 1).Trim());
if (exists)
{
continue;
}
else
{
filename = filesPath[b].Substring(filesPath[b].LastIndexOf('\\') + 1);
if (filename.Contains(ftpPrefix))
{
InsertData(downloadPath + filename);
importCount++;
flag = true;
}
}
}
if (importCount == 0)
{
RefreshLog(DateTime.Now + ":没有要导入的数据\r\n");
}
}
else
{
RefreshLog(DateTime.Now + ":没有要导入的数据\r\n");
}
}
catch (Exception e)
{
MessageBox.Show("下载文件出错:" + e.Message);
}
}
/// <summary>
/// <para>说明:向数据库插入数据</para>
/// <para>创建人:钱雄</para>
/// <para>创建日期:2020-11-10 </para>
/// <para>修改人:</para>
/// <para>修改日期:</para>
/// <para>修改备注:</para>
/// <para>版本:1.0</para>
/// </summary>
public void InsertData(string path)
{
Encoding FileCoding = GetFileEncodeType(path);//获取文件编码格式
string[] files = File.ReadAllLines(path.TrimEnd('\r'), FileCoding);//Encoding.Default
string fileName = path.Substring(path.LastIndexOf('\\') + 1).TrimEnd('\r').TrimEnd('\n').Trim();
RefreshLog(DateTime.Now + ":" + fileName + "文件读取中\r\n");
int wrongNumber = 1;//错误编号 1为拼接sql时错误,2为执行sql时错误
string errorContent = string.Empty;
try
{
string sqlValue = string.Empty;
string sqlValueAll = string.Empty;
//string data = string.Empty;
if (!prefixAndSql.ContainsKey(ftpPrefix))
{
RefreshLog("文件配置错误,文件名不匹配。\r\n");
return;
}
string sql = prefixAndSql[ftpPrefix];
sql = sql.Replace("{txtname}", fileName).Replace("{txtdate}", DateTime.Now.ToString());
if (files.Length > 0)
{
//string[] columnsData = new string[files[0].Split('~').Length];
int count = Regex.Matches(sql, @"\{[^\}]*\}").Count;
RefreshLog(DateTime.Now + ":开始拼接sql" + path + "\r\n");
for (int i = 0; i < files.Length; i++)
{
errorContent = files[i];
//string takleSql = "select ";
//for (int j = 0; j < files[i].Split('~').Length; j++)
//{
// //data = files[i].Split('~')[j];
// columnsData[j] = files[i].Split('~')[j];
// takleSql = takleSql + "'" + columnsData[j].Replace("'", "''") + "' as '" + j + "',";
//}
//takleSql = takleSql.Trim(',');
//DataTable table = OdbcHelper.ExecuteDataTable(takleSql);
//sqlValue = ReplaceRowParam(table.Rows[0], sql);
sqlValue = sql;
for (int j = 0; j <= count-1; j++)
{
//columnsData[j] = files[i].Split('~')[j];
string text = "";
if (files[i].Split('~').Length >= j+1)
{
text = files[i].Split('~')[j];
}
string key = "{" + j + "}";
sqlValue = sqlValue.Replace(key, text);
}
sqlValueAll += sqlValue + ";";
}
//254517
RefreshLog(DateTime.Now + ":" + fileName + "数据插入中\r\n");
wrongNumber = 2;
if (string.IsNullOrEmpty(sqlValueAll))
{
RefreshLog(DateTime.Now + ":" + "没有要插入的数据\r\n");
}
else
{
int counts = 0;
counts = OdbcHelper.ExecuteNonQuery(sqlValueAll);
if (counts > 0)
{
RefreshLog(DateTime.Now + ":" + "插入完成" + counts + "条\r\n");
RefreshLog(DateTime.Now + ":" + "正在移动\r\n");
//fileNames = path.Substring(path.LastIndexOf('\\') + 1).TrimEnd('\r').TrimEnd('\n').Trim();
StreamWriter sw = new StreamWriter(@txtFilePath, true);//true表示追加
sw.WriteLine(fileName);
sw.Flush();
sw.Close();
if (ftpHelper.fileDelete(fileName))
{
RefreshLog(DateTime.Now + ":ftp文件" + fileName + "删除成功\r\n");
}
if (!Directory.Exists(@movePath))
{
Directory.CreateDirectory(@movePath);//不存在就创建目录
}
else
{
if (FileUtilHelper.Move(path.Trim(), @movePath))
{
RefreshLog(DateTime.Now + ":" + "移动成功\r\n");
}
}
}
else
{
MessageBox.Show("插入失败");
}
}
}
else
{
RefreshLog(DateTime.Now + ":" + fileName + "没有数据\r\n");
//记录已经完成的文件
StreamWriter sw = new StreamWriter(@txtFilePath, true);//true表示追加
sw.WriteLine(fileName);
sw.Flush();
sw.Close();
if (ftpHelper.fileDelete(fileName))
{
RefreshLog(DateTime.Now + ":ftp文件" + fileName + "删除成功\r\n");
}
if (!Directory.Exists(@movePath))
{
Directory.CreateDirectory(@movePath);//不存在就创建目录
}
else
{
if (FileUtilHelper.Move(path.Trim(), @movePath))
{
RefreshLog(DateTime.Now + ":" + "移动成功\r\n");
}
}
}
}
catch (Exception ex)
{
if (wrongNumber == 1)
{
MessageBox.Show(DateTime.Now + ": 拼接Sql数据出错 :" + ex.Message);
writeLogException(ex, path + " : sql拼接错误 : " + errorContent);
}
else
{
MessageBox.Show(DateTime.Now + ": 向数据库插入数据出错 :" + ex.Message);
writeLogException(ex, path + " : " + "拼接sql执行错误");
}
}
}
//报错时写入日志操作
public static void writeLogException(Exception ex, string errorContent) //异常信息写入日志
{
//获取异常信息的类、行号、异常 信息
string exceptionStr = ex.StackTrace.ToString().Substring(ex.StackTrace.ToString().LastIndexOf('\\') + 1)
+ " " + ex.Message + " 报错内容:" + errorContent;
exceptionStr = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") + " " + exceptionStr;
//自己定义一个存储日志文件的位置
string sFilePath = PubUtil.AbsolutelyPath + "日志";
string sFileName = DateTime.Now.ToString("yyyy-MM-dd") + ".log";
sFileName = sFilePath + @"\\" + sFileName; //文件
if (!Directory.Exists(sFilePath))
{
Directory.CreateDirectory(sFilePath);
}
FileStream fs;
StreamWriter sw;
if (System.IO.File.Exists(sFileName))
{
fs = new FileStream(sFileName, FileMode.Append, FileAccess.Write);
}
else
{
fs = new FileStream(sFileName, FileMode.Create, FileAccess.Write);
}
sw = new StreamWriter(fs);
sw.WriteLine(exceptionStr);
sw.Close();
fs.Close();
}
/// <summary>
/// 判断文件格式(ANSI和utf-8
/// </summary>
/// <param name="filename"></param>
/// <returns></returns>
public System.Text.Encoding GetFileEncodeType(string filename)
{
try
{
filename = filename.Replace("\r", "");
using (FileStream fs = new FileStream(filename, System.IO.FileMode.Open, System.IO.FileAccess.Read))
{
byte[] Unicode = new byte[] { 0xFF, 0xFE, 0x41 };
byte[] UnicodeBIG = new byte[] { 0xFE, 0xFF, 0x00 };
byte[] UTF8 = new byte[] { 0xEF, 0xBB, 0xBF };//带BOM
Encoding reVal = Encoding.Default;
BinaryReader br = new BinaryReader(fs);
int length;
int.TryParse(fs.Length.ToString(), out length);
byte[] ss = br.ReadBytes(length);
if (IsUTF8Bytes(ss) ||
(ss[0] == UTF8[0] && ss[1] == UTF8[1] && ss[2] == UTF8[2]))
reVal = Encoding.UTF8;
else if (ss[0] == UnicodeBIG[0] && ss[1] == UnicodeBIG[1] && ss[2] == UnicodeBIG[2])
reVal = Encoding.BigEndianUnicode;
else if (ss[0] == Unicode[0] && ss[1] == Unicode[1] && ss[2] == Unicode[2])
reVal = Encoding.Unicode;
br.Close();
return reVal;
}
}
catch (Exception ex)
{
RefreshLog(DateTime.Now + ":" + filename + "获取编码格式失败,使用电脑默认编码格式\r\n");
return Encoding.Default;
}
}
/// <summary>
/// 判断是否是不带 BOM 的 UTF8 格式
/// </summary>
/// <param name=“data“></param>
/// <returns></returns>
private static bool IsUTF8Bytes(byte[] data)
{
int charByteCounter = 1;//计算当前正分析的字符应还有的字节数
byte curByte;//当前分析的字节
for (int i = 0; i < data.Length; i++)
{
curByte = data[i];
if (charByteCounter == 1)
{
if (curByte >= 0x80)
{
//判断当前
while (((curByte <<= 1) & 0x80) != 0)
{
charByteCounter++;
}
//标记位首位若为非0 则至少以2个1开始,如:110XXXXX.....1111110X
if (charByteCounter == 1 || charByteCounter > 6)
{
return false;
}
}
}
else
{
//若是UTF-8 此时第一位必须为1
if ((curByte & 0xC0) != 0x80)
{
return false;
}
charByteCounter--;
}
}
if (charByteCounter > 1)
{
throw new Exception("非预期的byte格式");
}
return true;
}
/// <summary>
/// <para>说明:说明:替换"{字段}"格式字符串,已替换操作员等信息</para>
/// <para>创建人:龚宇超</para>
/// <para>创建日期:2017-10-30 </para>
/// <para>修改人:</para>
/// <para>修改日期:</para>
/// <para>修改备注:</para>
/// <para>版本:1.0</para>
/// </summary>
/// <param name="row">The row.</param>
/// <param name="param">The parameter.</param>
/// <returns>System.String.</returns>
public static string ReplaceRowParam(DataRow row, string param)
{
if (row == null) return param;
List<string> condition = GetParamFields(param);
foreach (string item in condition)
{
string field = item.Replace("{", "").Replace("}", "");
string value = row.Table.Columns.Contains(field) ? row[field] + "" : item;
value = value.Replace("'", "''");
param = param.Replace(item, value);
}
return param;
}
/// <summary>
/// <para>说明:获取sql语句中替换</para>
/// <para>创建人:龚宇超</para>
/// <para>创建日期:2017-09-04 </para>
/// <para>修改人:</para>
/// <para>修改日期:</para>
/// <para>修改备注:</para>
/// <para>版本:1.0</para>
/// </summary>
/// <returns>List&lt;System.String&gt;.</returns>
public static List<string> GetParamFields(string defaultValue)
{
List<string> list = new List<string>();
Regex regex = new Regex("{([^{])+}");
MatchCollection mcs = regex.Matches(defaultValue);
foreach (Match item in mcs)
{
if (list.IndexOf(item.Value) == -1)
list.Add(item.Value);
}
return list;
}
}
}
+120
View File
@@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>
+652
View File
@@ -0,0 +1,652 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Windows.Forms;
using System.Configuration;
using System.Data;
namespace Lskj.TxtFileRead
{
public class FtpHelper
{
static string ftpServerIP;
static string ftpRemotePath;
static string ftpUserID;
static string ftpPassword;
static string ftpURI;
/// <summary>
/// 连接FTP
/// </summary>
/// <param name="FtpServerIP">FTP连接地址</param>
/// <param name="FtpRemotePath">指定FTP连接成功后的当前目录, 如果不指定即默认为根目录</param>
/// <param name="FtpUserID">用户名</param>
/// <param name="FtpPassword">密码</param>
public FtpHelper(string FtpServerIP, string FtpRemotePath, string FtpUserID, string FtpPassword)
{
ftpServerIP = FtpServerIP;
ftpRemotePath = FtpRemotePath;
ftpUserID = FtpUserID;
ftpPassword = FtpPassword;
ftpURI = @"ftp://" + ftpServerIP + "/" + ftpRemotePath + "/";
}
/// <summary>
/// 从ftp服务器上获取文件并将内容全部转换成string返回
/// </summary>
/// <param name="fileName"></param>
/// <param name="dir"></param>
/// <returns></returns>
public string GetFileStr(string fileName, string dir)
{
FtpWebRequest reqFTP;
try
{
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + fileName));
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpURI);
reqFTP.UsePassive = false; //选择主动还是被动模式 , 这句要加上的。
reqFTP.KeepAlive = false;//一定要设置此属性,否则一次性下载多个文件的时候,会出现异常。
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream ftpStream = response.GetResponseStream();
StreamReader reader = new StreamReader(ftpStream);
string fileStr = reader.ReadToEnd();
reader.Close();
ftpStream.Close();
response.Close();
return fileStr;
}
catch (Exception ex)
{
MessageBox.Show("获取ftp文件并读取内容失败:" + ex.Message);
return null;
}
}
/// <summary>
/// 下载
/// </summary>
/// <param name="filePath"></param>
/// <param name="fileName"></param>
public void Download(string filePath, string fileName)
{
try
{
FileStream outputStream = new FileStream(@filePath + "\\" + fileName, FileMode.Create);
FtpWebRequest reqFTP;
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + fileName));
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
reqFTP.UseBinary = true;
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream ftpStream = response.GetResponseStream();
long cl = response.ContentLength;
int bufferSize = 2048;
int readCount;
byte[] buffer = new byte[bufferSize];
readCount = ftpStream.Read(buffer, 0, bufferSize);
while (readCount > 0)
{
outputStream.Write(buffer, 0, readCount);
readCount = ftpStream.Read(buffer, 0, bufferSize);
}
ftpStream.Close();
outputStream.Close();
response.Close();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
/// <summary>
/// 删除文件
/// </summary>
/// <param name="filePath"></param>
public bool fileDelete(string ftpfileName)
{
bool success = false;
FtpWebRequest ftpWebRequest = null;
FtpWebResponse ftpWebResponse = null;
Stream ftpResponseStream = null;
StreamReader streamReader = null;
try
{
string uri = ftpURI + ftpfileName;
ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
ftpWebRequest.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
ftpWebRequest.KeepAlive = false;
ftpWebRequest.Method = WebRequestMethods.Ftp.DeleteFile;
ftpWebResponse = (FtpWebResponse)ftpWebRequest.GetResponse();
long size = ftpWebResponse.ContentLength;
ftpResponseStream = ftpWebResponse.GetResponseStream();
streamReader = new StreamReader(ftpResponseStream);
string result = String.Empty;
result = streamReader.ReadToEnd();
success = true;
}
catch (Exception)
{
success = false;
}
finally
{
if (streamReader != null)
{
streamReader.Close();
}
if (ftpResponseStream != null)
{
ftpResponseStream.Close();
}
if (ftpWebResponse != null)
{
ftpWebResponse.Close();
}
}
return success;
}
//获取ftp上面的文件和文件夹
public string[] GetFileList()
{
string[] downloadFiles;
StringBuilder result = new StringBuilder();
FtpWebRequest request;
try
{
request = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI));
request.UseBinary = true;
request.Credentials = new NetworkCredential(ftpUserID, ftpPassword);//设置用户名和密码
request.Method = WebRequestMethods.Ftp.ListDirectory;
request.UseBinary = true;
request.UsePassive = false; //选择主动还是被动模式 , 这句要加上的。
request.KeepAlive = false;//一定要设置此属性,否则一次性下载多个文件的时候,会出现异常。
WebResponse response = request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string line = reader.ReadLine();
while (line != null)
{
result.Append(line);
result.Append("\n");
line = reader.ReadLine();
}
result.Remove(result.ToString().LastIndexOf('\n'), 1);
reader.Close();
response.Close();
return result.ToString().Split('\n');
}
catch (Exception ex)
{
MessageBox.Show("获取ftp上面的文件和文件夹:" + ex.Message);
downloadFiles = null;
return downloadFiles;
}
}
public List<string> GetAllList()
{
List<string> list = new List<string>();
FtpWebRequest req = (FtpWebRequest)WebRequest.Create(new Uri(ftpURI));
req.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
req.Method = WebRequestMethods.Ftp.ListDirectory;
req.UseBinary = true;
req.UsePassive = true;
try
{
using (FtpWebResponse res = (FtpWebResponse)req.GetResponse())
{
using (StreamReader sr = new StreamReader(res.GetResponseStream()))
{
string s;
while ((s = sr.ReadLine()) != null)
{
list.Add(s);
}
}
}
}
catch (Exception ex)
{
throw (ex);
}
return list;
}
/// <summary>
/// 获取当前目录下明细(包含文件和文件夹)
/// </summary>
public string[] GetFilesDetailList()
{
try
{
StringBuilder result = new StringBuilder();
FtpWebRequest ftp;
ftp = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI));
ftp.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
WebResponse response = ftp.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string line = reader.ReadLine();
line = reader.ReadLine();
line = reader.ReadLine();
while (line != null)
{
result.Append(line);
result.Append("\n");
line = reader.ReadLine();
}
result.Remove(result.ToString().LastIndexOf("\n"), 1);
reader.Close();
response.Close();
return result.ToString().Split('\n');
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
/// <summary>
/// 获取指定文件大小
/// </summary>
public long GetFileSize(string filename)
{
FtpWebRequest reqFTP;
long fileSize = 0;
try
{
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + filename));
reqFTP.Method = WebRequestMethods.Ftp.GetFileSize;
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream ftpStream = response.GetResponseStream();
fileSize = response.ContentLength;
ftpStream.Close();
response.Close();
}
catch (Exception ex)
{ }
return fileSize;
}
/// <summary>
/// 创建文件夹
/// </summary>
public void MakeDir(string dirName)
{
FtpWebRequest reqFTP;
try
{
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + dirName));
reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream ftpStream = response.GetResponseStream();
ftpStream.Close();
response.Close();
}
catch (Exception ex)
{ }
}
/// <summary>
/// 删除文件
/// </summary>
public void Delete(string fileName)
{
try
{
FtpWebRequest reqFTP;
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + fileName));
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;
reqFTP.KeepAlive = false;
string result = String.Empty;
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
long size = response.ContentLength;
Stream datastream = response.GetResponseStream();
StreamReader sr = new StreamReader(datastream);
result = sr.ReadToEnd();
sr.Close();
datastream.Close();
response.Close();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
/// <summary>
/// 上传
/// </summary>
public void Upload(string filename)
{
FileInfo fileInf = new FileInfo(filename);
FtpWebRequest reqFTP;
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + fileInf.Name));
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
reqFTP.KeepAlive = false;
reqFTP.UseBinary = true;
reqFTP.ContentLength = fileInf.Length;
int buffLength = 2048;
byte[] buff = new byte[buffLength];
int contentLen;
FileStream fs = fileInf.OpenRead();
try
{
Stream strm = reqFTP.GetRequestStream();
contentLen = fs.Read(buff, 0, buffLength);
while (contentLen != 0)
{
strm.Write(buff, 0, contentLen);
contentLen = fs.Read(buff, 0, buffLength);
}
strm.Close();
fs.Close();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
#region FTP服务器下载文件
/// <summary>
/// 从FTP服务器下载文件,指定本地路径和本地文件名
/// </summary>
/// <param name="remoteFileName">远程文件名</param>
/// <param name="localFileName">保存本地的文件名(包含路径)</param>
/// <param name="ifCredential">是否启用身份验证(false:表示允许用户匿名下载)</param>
/// <param name="updateProgress">报告进度的处理(第一个参数:总大小,第二个参数:当前进度)</param>
/// <returns>是否下载成功</returns>
public bool FtpDownload(string remoteFileName, string localFileName, bool ifCredential, Action<int, int> updateProgress = null)
{
FtpWebRequest reqFTP, ftpsize;
Stream ftpStream = null;
FtpWebResponse response = null;
FileStream outputStream = null;
try
{
outputStream = new FileStream(localFileName, FileMode.Create);
Uri uri = new Uri(@"ftp://" + ftpServerIP + "/" + remoteFileName);
ftpsize = (FtpWebRequest)FtpWebRequest.Create(uri);
ftpsize.UseBinary = true;
reqFTP = (FtpWebRequest)FtpWebRequest.Create(uri);
reqFTP.UseBinary = true;
reqFTP.KeepAlive = false;
if (ifCredential)//使用用户身份认证
{
ftpsize.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
}
ftpsize.Method = WebRequestMethods.Ftp.GetFileSize;
FtpWebResponse re = (FtpWebResponse)ftpsize.GetResponse();
long totalBytes = re.ContentLength;
re.Close();
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
response = (FtpWebResponse)reqFTP.GetResponse();
ftpStream = response.GetResponseStream();
//更新进度
if (updateProgress != null)
{
updateProgress((int)totalBytes, 0);//更新进度条
}
long totalDownloadedByte = 0;
int bufferSize = 2048;
int readCount;
byte[] buffer = new byte[bufferSize];
readCount = ftpStream.Read(buffer, 0, bufferSize);
while (readCount > 0)
{
totalDownloadedByte = readCount + totalDownloadedByte;
outputStream.Write(buffer, 0, readCount);
//更新进度
if (updateProgress != null)
{
updateProgress((int)totalBytes, (int)totalDownloadedByte);//更新进度条
}
readCount = ftpStream.Read(buffer, 0, bufferSize);
}
ftpStream.Close();
outputStream.Close();
response.Close();
return true;
}
catch (Exception ex)
{
MessageBox.Show("下载文件出现;" + ex.Message);
return false;
throw;
}
finally
{
if (ftpStream != null)
{
ftpStream.Close();
}
if (outputStream != null)
{
outputStream.Close();
}
if (response != null)
{
response.Close();
}
}
}
/// <summary>
/// 从FTP服务器下载文件,指定本地路径和本地文件名(支持断点下载)
/// </summary>
/// <param name="remoteFileName">远程文件名</param>
/// <param name="localFileName">保存本地的文件名(包含路径)</param>
/// <param name="ifCredential">是否启用身份验证(false:表示允许用户匿名下载)</param>
/// <param name="size">已下载文件流大小</param>
/// <param name="updateProgress">报告进度的处理(第一个参数:总大小,第二个参数:当前进度)</param>
/// <returns>是否下载成功</returns>
public static bool FtpBrokenDownload(string remoteFileName, string localFileName, bool ifCredential, long size, Action<int, int> updateProgress = null)
{
FtpWebRequest reqFTP, ftpsize;
Stream ftpStream = null;
FtpWebResponse response = null;
FileStream outputStream = null;
try
{
outputStream = new FileStream(localFileName, FileMode.Append);
Uri uri = new Uri(@"ftp://" + ftpServerIP + "/" + remoteFileName);
ftpsize = (FtpWebRequest)FtpWebRequest.Create(uri);
ftpsize.UseBinary = true;
ftpsize.ContentOffset = size;
reqFTP = (FtpWebRequest)FtpWebRequest.Create(uri);
reqFTP.UseBinary = true;
reqFTP.KeepAlive = false;
reqFTP.ContentOffset = size;
if (ifCredential)//使用用户身份认证
{
ftpsize.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
}
ftpsize.Method = WebRequestMethods.Ftp.GetFileSize;
FtpWebResponse re = (FtpWebResponse)ftpsize.GetResponse();
long totalBytes = re.ContentLength;
re.Close();
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
response = (FtpWebResponse)reqFTP.GetResponse();
ftpStream = response.GetResponseStream();
//更新进度
if (updateProgress != null)
{
updateProgress((int)totalBytes, 0);//更新进度条
}
long totalDownloadedByte = 0;
int bufferSize = 2048;
int readCount;
byte[] buffer = new byte[bufferSize];
readCount = ftpStream.Read(buffer, 0, bufferSize);
while (readCount > 0)
{
totalDownloadedByte = readCount + totalDownloadedByte;
outputStream.Write(buffer, 0, readCount);
//更新进度
if (updateProgress != null)
{
updateProgress((int)totalBytes, (int)totalDownloadedByte);//更新进度条
}
readCount = ftpStream.Read(buffer, 0, bufferSize);
}
ftpStream.Close();
outputStream.Close();
response.Close();
return true;
}
catch (Exception ex)
{
MessageBox.Show("下载文件出现;" + ex.Message);
return false;
throw;
}
finally
{
if (ftpStream != null)
{
ftpStream.Close();
}
if (outputStream != null)
{
outputStream.Close();
}
if (response != null)
{
response.Close();
}
}
}
/// <summary>
/// 从FTP服务器下载文件,指定本地路径和本地文件名
/// </summary>
/// <param name="remoteFileName">远程文件名</param>
/// <param name="localFileName">保存本地的文件名(包含路径)</param>
/// <param name="ifCredential">是否启用身份验证(false:表示允许用户匿名下载)</param>
/// <param name="updateProgress">报告进度的处理(第一个参数:总大小,第二个参数:当前进度)</param>
/// <param name="brokenOpen">是否断点下载:true 会在localFileName 找是否存在已经下载的文件,并计算文件流大小</param>
/// <returns>是否下载成功</returns>
public bool FtpDownload(string remoteFileName, string localFileName, bool ifCredential, bool brokenOpen, Action<int, int> updateProgress = null)
{
if (brokenOpen)
{
try
{
long size = 0;
if (File.Exists(localFileName))
{
using (FileStream outputStream = new FileStream(localFileName, FileMode.Open))
{
size = outputStream.Length;
}
}
return FtpBrokenDownload(remoteFileName, localFileName, ifCredential, size, updateProgress);
}
catch
{
throw;
}
}
else
{
return FtpDownload(remoteFileName, localFileName, ifCredential, updateProgress);
}
}
#endregion
/// <summary>
/// 获取本地某个文件夹下的文件
/// <summary>
public string[] GetFiles(DirectoryInfo directory, string pattern)
{
StringBuilder sb = new StringBuilder();
if (directory.Exists || pattern.Trim() != string.Empty)
{
foreach (FileInfo info in directory.GetFiles(pattern))
{
sb.AppendLine(info.FullName.ToString());
}
foreach (DirectoryInfo info in directory.GetDirectories())
{
GetFiles(info, pattern);
}
}
sb.Remove(sb.ToString().LastIndexOf("\n"), 1);
return sb.ToString().Split('\n');
}
/// <summary>
/// 接删除指定目录下的所有文件及文件夹(保留目录)
/// <summary>
public static void DeleteDir(string file)
{
try
{
//去除文件夹和子文件的只读属性
//去除文件夹的只读属性
System.IO.DirectoryInfo fileInfo = new DirectoryInfo(file);
fileInfo.Attributes = FileAttributes.Normal & FileAttributes.Directory;
//去除文件的只读属性
System.IO.File.SetAttributes(file, System.IO.FileAttributes.Normal);
//判断文件夹是否还存在
if (Directory.Exists(file))
{
foreach (string f in Directory.GetFileSystemEntries(file))
{
if (File.Exists(f))
{
//如果有子文件删除文件
File.Delete(f);
Console.WriteLine(f);
}
else
{
//循环递归删除子文件夹
DeleteDir(f);
}
}
//删除空文件夹
//Directory.Delete(file);
Console.WriteLine(file);
}
}
catch (Exception ex) // 异常处理
{
Console.WriteLine(ex.Message.ToString());// 异常信息
}
}
}
}
+176
View File
@@ -0,0 +1,176 @@
/******************************
* 说明:Ini 文件操作类
* 创建人:龚宇超
* 创建日期:2017-07-22
* 修改人:
* 修改日期:
* 修改备注:
* 版本:1.0.0.0
******************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.IO;
using System.Windows.Forms;
namespace Lskj.TxtFileRead
{
/// <summary>
/// Ini 文件操作类
/// </summary>
public static class IniHelper
{
/// <summary>
/// 写入INI文件
/// </summary>
/// <param name="section">节点名称[如[TypeName]]</param>
/// <param name="key">键</param>
/// <param name="val">值</param>
/// <param name="filepath">文件路径</param>
/// <returns></returns>
[DllImport("kernel32")]
private static extern long WritePrivateProfileString(string section, string key, string val, string filepath);
/// <summary>
/// 读取INI文件
/// </summary>
/// <param name="section">节点名称</param>
/// <param name="key">键</param>
/// <param name="def">值</param>
/// <param name="retval">stringbulider对象</param>
/// <param name="size">字节大小</param>
/// <param name="filePath">文件路径</param>
/// <returns></returns>
[DllImport("kernel32")]
private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retval, int size, string filePath);
/// <summary>
/// <para>说明:写入Ini文件(以键值对的形式存放)</para>
/// <para>创建人:龚宇超</para>
/// <para>创建日期:2017-07-22</para>
/// <para>修改人:</para>
/// <para>修改日期:</para>
/// <para>修改备注:</para>
/// <para>版本:1.0</para>
/// </summary>
/// <param name="key">键</param>
/// <param name="value">值</param>
/// <returns></returns>
public static void Write(string key, string value)
{
try
{
//根据INI文件名设置要写入INI文件的节点名称
//此处的节点名称完全可以根据实际需要进行配置
string filePath = PubUtil.MainMenuConfigPath;
if (!File.Exists(filePath))
{
File.Create(filePath);
}
string fileName = Path.GetFileNameWithoutExtension(filePath);
WritePrivateProfileString(fileName, key, value, filePath);
}
catch (Exception ex)
{
}
}
/// <summary>
/// <para>说明:通过Key获取Value值</para>
/// <para>创建人:龚宇超</para>
/// <para>创建日期:2017-07-22</para>
/// <para>修改人:</para>
/// <para>修改日期:</para>
/// <para>修改备注:</para>
/// <para>版本:1.0</para>
/// </summary>
/// <param name="key">键</param>
/// <returns>值</returns>
public static string Read(string key)
{
string value = string.Empty;
try
{
//判读INI文件是否存在
string filePath = PubUtil.MainMenuConfigPath;
if (File.Exists(filePath))
{
StringBuilder temp = new StringBuilder(1024);
string fileName = Path.GetFileNameWithoutExtension(filePath);
GetPrivateProfileString(fileName, key, "", temp, 1024, filePath);
return temp + "";
}
}
catch (Exception)
{
}
return value;
}
/// <summary>
/// <para>说明:写入Ini文件(以键值对的形式存放)</para>
/// <para>创建人:龚宇超</para>
/// <para>创建日期:2017-07-22</para>
/// <para>修改人:</para>
/// <para>修改日期:</para>
/// <para>修改备注:</para>
/// <para>版本:1.0</para>
/// </summary>
/// <param name="key">键</param>
/// <param name="value">值</param>
/// <returns></returns>
public static void Write(string iniName,string key, string value)
{
try
{
//根据INI文件名设置要写入INI文件的节点名称
//此处的节点名称完全可以根据实际需要进行配置
string filePath = Path.Combine(new string[] { PubUtil.AbsolutelyPath + iniName });
if (!File.Exists(filePath))
{
File.Create(filePath);
}
string fileName = Path.GetFileNameWithoutExtension(filePath);
WritePrivateProfileString(fileName, key, value, filePath);
}
catch (Exception ex)
{
}
}
/// <summary>
/// <para>说明:通过Key获取Value值</para>
/// <para>创建人:龚宇超</para>
/// <para>创建日期:2017-07-22</para>
/// <para>修改人:</para>
/// <para>修改日期:</para>
/// <para>修改备注:</para>
/// <para>版本:1.0</para>
/// </summary>
/// <param name="key">键</param>
/// <returns>值</returns>
public static string Read(string iniName,string key)
{
string value = string.Empty;
try
{
//判读INI文件是否存在
string filePath = Path.Combine(new string[] { PubUtil.AbsolutelyPath + iniName });
if (File.Exists(filePath))
{
StringBuilder temp = new StringBuilder(1024);
string fileName = Path.GetFileNameWithoutExtension(filePath);
GetPrivateProfileString(fileName, key, "", temp, 2048, filePath);
return temp + "";
}
}
catch (Exception)
{
}
return value;
}
}
}
@@ -0,0 +1,152 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">x86</Platform>
<ProductVersion>8.0.30703</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{B4F1E41F-0A1B-48BF-BF9F-EA2DB8B6400D}</ProjectGuid>
<OutputType>WinExe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Lskj.TxtFileRead</RootNamespace>
<AssemblyName>Lskj.TxtFileRead</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<TargetFrameworkProfile>
</TargetFrameworkProfile>
<FileAlignment>512</FileAlignment>
<PublishUrl>publish\</PublishUrl>
<Install>true</Install>
<InstallFrom>Disk</InstallFrom>
<UpdateEnabled>false</UpdateEnabled>
<UpdateMode>Foreground</UpdateMode>
<UpdateInterval>7</UpdateInterval>
<UpdateIntervalUnits>Days</UpdateIntervalUnits>
<UpdatePeriodically>false</UpdatePeriodically>
<UpdateRequired>false</UpdateRequired>
<MapFileExtensions>true</MapFileExtensions>
<ApplicationRevision>0</ApplicationRevision>
<ApplicationVersion>1.0.0.%2a</ApplicationVersion>
<IsWebBootstrapper>false</IsWebBootstrapper>
<UseApplicationTrust>false</UseApplicationTrust>
<BootstrapperEnabled>true</BootstrapperEnabled>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
<PlatformTarget>x86</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
<PlatformTarget>x86</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup>
<ApplicationIcon>logo.ico</ApplicationIcon>
</PropertyGroup>
<ItemGroup>
<Reference Include="DevExpress.Data.v15.2, Version=15.2.4.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a, processorArchitecture=MSIL" />
<Reference Include="DevExpress.Printing.v15.2.Core, Version=15.2.4.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a, processorArchitecture=MSIL" />
<Reference Include="DevExpress.Sparkline.v15.2.Core, Version=15.2.4.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a, processorArchitecture=MSIL" />
<Reference Include="DevExpress.Utils.v15.2, Version=15.2.4.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a, processorArchitecture=MSIL" />
<Reference Include="DevExpress.XtraEditors.v15.2, Version=15.2.4.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a, processorArchitecture=MSIL" />
<Reference Include="PresentationCore" />
<Reference Include="System" />
<Reference Include="System.ComponentModel.DataAnnotations" />
<Reference Include="System.Data.Linq" />
<Reference Include="System.Runtime.Remoting" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Deployment" />
<Reference Include="System.Drawing" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml" />
<Reference Include="UIAutomationClient" />
<Reference Include="WindowsBase" />
</ItemGroup>
<ItemGroup>
<Compile Include="AESUtil.cs" />
<Compile Include="DBConfig.cs" />
<Compile Include="FileUtilHelper.cs" />
<Compile Include="FrmMain.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="FrmMain.Designer.cs">
<DependentUpon>FrmMain.cs</DependentUpon>
</Compile>
<Compile Include="FtpHelper.cs" />
<Compile Include="IniHelper.cs" />
<Compile Include="OdbcHelper.cs" />
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="PubUtil.cs" />
<Compile Include="SqlHelper.cs" />
<EmbeddedResource Include="FrmMain.resx">
<DependentUpon>FrmMain.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="Properties\licenses.licx" />
<EmbeddedResource Include="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
<SubType>Designer</SubType>
</EmbeddedResource>
<Compile Include="Properties\Resources.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
<DesignTime>True</DesignTime>
</Compile>
<None Include="app.config" />
<None Include="Properties\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<LastGenOutput>Settings.Designer.cs</LastGenOutput>
</None>
<Compile Include="Properties\Settings.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
</ItemGroup>
<ItemGroup>
<BootstrapperPackage Include=".NETFramework,Version=v4.0">
<Visible>False</Visible>
<ProductName>Microsoft .NET Framework 4 %28x86 和 x64%29</ProductName>
<Install>true</Install>
</BootstrapperPackage>
<BootstrapperPackage Include="Microsoft.Net.Client.3.5">
<Visible>False</Visible>
<ProductName>.NET Framework 3.5 SP1 Client Profile</ProductName>
<Install>false</Install>
</BootstrapperPackage>
<BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">
<Visible>False</Visible>
<ProductName>.NET Framework 3.5 SP1</ProductName>
<Install>false</Install>
</BootstrapperPackage>
<BootstrapperPackage Include="Microsoft.Windows.Installer.3.1">
<Visible>False</Visible>
<ProductName>Windows Installer 3.1</ProductName>
<Install>true</Install>
</BootstrapperPackage>
</ItemGroup>
<ItemGroup>
<Content Include="logo.ico" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>
@@ -0,0 +1,20 @@
Microsoft Visual Studio Solution File, Format Version 11.00
# Visual Studio 2010
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lskj.TxtFileRead", "Lskj.TxtFileRead.csproj", "{B4F1E41F-0A1B-48BF-BF9F-EA2DB8B6400D}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x86 = Debug|x86
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{B4F1E41F-0A1B-48BF-BF9F-EA2DB8B6400D}.Debug|x86.ActiveCfg = Debug|x86
{B4F1E41F-0A1B-48BF-BF9F-EA2DB8B6400D}.Debug|x86.Build.0 = Debug|x86
{B4F1E41F-0A1B-48BF-BF9F-EA2DB8B6400D}.Release|x86.ActiveCfg = Release|x86
{B4F1E41F-0A1B-48BF-BF9F-EA2DB8B6400D}.Release|x86.Build.0 = Release|x86
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
+606
View File
@@ -0,0 +1,606 @@
/******************************
* 说明:数据库操作类
* 创建人:龚宇超
* 创建日期:2017-07-24
* 修改人:
* 修改日期:
* 修改备注:
* 版本:1.0.0.0
******************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using System.Data.Odbc;
namespace Lskj.Core
{
/// <summary>
/// 数据库操作类
/// </summary>
public static class OdbcHelper
{
/// <summary>
/// 数据连接
/// </summary>
public static OdbcConnection _connection;//SqlConnection
/// <summary>
/// 请求超时时间
/// </summary>
public static int CommandTimeout;
//#region ExecuteAdapter
///// <summary>
///// <para>说明:获取适配器</para>
///// <para>创建人:龚宇超</para>
///// <para>创建日期:2017-07-24 </para>
///// <para>修改人:</para>
///// <para>修改日期:</para>
///// <para>修改备注:</para>
///// <para>版本:1.0</para>
///// </summary>
///// <param name="cmdType">Type of the command.</param>
///// <param name="cmdText">The command text.</param>
///// <param name="commandParameters">The command parameters.</param>
///// <returns>SqlDataAdapter.</returns>
//public static OdbcDataAdapter ExecuteAdapter(CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
//{
// OdbcDataAdapter adapter;
// OdbcCommand cmd = new OdbcCommand();
// try
// {
// PrepareCommand(cmd, _connection, null, cmdType, cmdText, commandParameters);
// adapter = new OdbcDataAdapter(cmd);
// }
// catch
// {
// throw;
// }
// return adapter;
//}
///// <summary>
///// <para>说明:获取适配器</para>
///// <para>创建人:龚宇超</para>
///// <para>创建日期:2017-07-24 </para>
///// <para>修改人:</para>
///// <para>修改日期:</para>
///// <para>修改备注:</para>
///// <para>版本:1.0</para>
///// </summary>
///// <param name="cmdType">Type of the command.</param>
///// <param name="cmdText">The command text.</param>
///// <returns>SqlDataAdapter.</returns>
//public static OdbcDataAdapter ExecuteAdapter(CommandType cmdType, string cmdText)
//{
// OdbcDataAdapter adapter;
// OdbcCommand cmd = new OdbcCommand();
// try
// {
// PrepareCommand(cmd, _connection, null, cmdType, cmdText, null);
// adapter = new OdbcDataAdapter(cmd);
// }
// catch
// {
// throw;
// }
// return adapter;
//}
//#endregion
//#region ExecuteDataTable
///// <summary>
///// <para>说明:执行sql返回DataTable</para>
///// <para>创建人:龚宇超</para>
///// <para>创建日期:2017-07-24 </para>
///// <para>修改人:</para>
///// <para>修改日期:</para>
///// <para>修改备注:</para>
///// <para>版本:1.0</para>
///// </summary>
///// <param name="cmdText">The command text.</param>
///// <returns>DataTable.</returns>
public static DataTable ExecuteDataTable(string cmdText)
{
return ExecuteDataSet(cmdText).Tables[0];
}
///// <summary>
///// <para>说明:执行sql返回DataTable</para>
///// <para>创建人:龚宇超</para>
///// <para>创建日期:2017-07-24 </para>
///// <para>修改人:</para>
///// <para>修改日期:</para>
///// <para>修改备注:</para>
///// <para>版本:1.0</para>
///// </summary>
///// <param name="cmdText">The command text.</param>
///// <returns>DataTable.</returns>
//public static DataTable ExecuteDataTable(string cmdText, params SqlParameter[] commandParameters)
//{
// return ExecuteDataSet(CommandType.Text, cmdText, "temp", commandParameters).Tables[0];
//}
///// <summary>
///// <para>说明:执行sql返回指定字段值</para>
///// <para>创建人:龚宇超</para>
///// <para>创建日期:2017-08-15 </para>
///// <para>修改人:</para>
///// <para>修改日期:</para>
///// <para>修改备注:</para>
///// <para>版本:1.0</para>
///// </summary>
///// <param name="fieldName">Name of the field.</param>
///// <param name="cmdText">The command text.</param>
///// <returns>System.Object.</returns>
//public static object ExecuteObject(string fieldName, string cmdText)
//{
// object result = null;
// try
// {
// result = ExecuteDataSet(cmdText).Tables[0].Rows[0][fieldName];
// }
// catch (Exception)
// {
// }
// return result;
//}
///// <summary>
///// <para>说明:执行sql返回指定字段值</para>
///// <para>创建人:龚宇超</para>
///// <para>创建日期:2017-11-27 </para>
///// <para>修改人:</para>
///// <para>修改日期:</para>
///// <para>修改备注:</para>
///// <para>版本:1.0</para>
///// </summary>
///// <param name="fieldName">Name of the field.</param>
///// <param name="cmdText">The command text.</param>
///// <param name="commandParameters">The command parameters.</param>
///// <returns>System.Object.</returns>
//public static object ExecuteObject(string fieldName, string cmdText, params SqlParameter[] commandParameters)
//{
// object result = null;
// try
// {
// result = ExecuteDataSet(CommandType.Text, cmdText, "temp", commandParameters).Tables[0].Rows[0][fieldName];
// }
// catch (Exception)
// {
// }
// return result;
//}
///// <summary>
///// <para>说明:执行sql返回指定字段值</para>
///// <para>创建人:龚宇超</para>
///// <para>创建日期:2017-08-15 </para>
///// <para>修改人:</para>
///// <para>修改日期:</para>
///// <para>修改备注:</para>
///// <para>版本:1.0</para>
///// </summary>
///// <param name="fieldName">Name of the field.</param>
///// <param name="cmdText">The command text.</param>
///// <returns>System.Object.</returns>
//public static string ExecuteString(string fieldName, string cmdText)
//{
// object obj = ExecuteObject(fieldName, cmdText);
// return obj == null ? "" : obj.ToString();
//}
///// <summary>
///// <para>说明:执行sql返回指定字段值</para>
///// <para>创建人:龚宇超</para>
///// <para>创建日期:2017-11-27 </para>
///// <para>修改人:</para>
///// <para>修改日期:</para>
///// <para>修改备注:</para>
///// <para>版本:1.0</para>
///// </summary>
///// <param name="fieldName">Name of the field.</param>
///// <param name="cmdText">The command text.</param>
///// <param name="commandParameters">The command parameters.</param>
///// <returns>System.String.</returns>
//public static string ExecuteString(string fieldName, string cmdText, params SqlParameter[] commandParameters)
//{
// object obj = ExecuteObject(fieldName, cmdText, commandParameters);
// return obj == null ? "" : obj.ToString();
//}
//#endregion
//#region ExecuteDataSet
///// <summary>
///// <para>说明:查询结果集</para>
///// <para>创建人:龚宇超</para>
///// <para>创建日期:2017-07-24 </para>
///// <para>修改人:</para>
///// <para>修改日期:</para>
///// <para>修改备注:</para>
///// <para>版本:1.0</para>
///// </summary>
///// <param name="cmdType">Type of the command.</param>
///// <param name="cmdText">The command text.</param>
///// <param name="tabName">Name of the tab.</param>
///// <param name="commandParameters">The command parameters.</param>
///// <returns>DataSet.</returns>
//public static DataSet ExecuteDataSet(int cmdType, string cmdText, string tabName, params SqlParameter[] commandParameters)
//{
// CommandType _cmdType = CommandType.Text;
// switch (cmdType)
// {
// case 4:
// _cmdType = CommandType.StoredProcedure;
// break;
// case 512:
// _cmdType = CommandType.TableDirect;
// break;
// }
// return ExecuteDataSet(_cmdType, cmdText, tabName, commandParameters);
//}
///// <summary>
///// <para>说明:查询结果集</para>
///// <para>创建人:龚宇超</para>
///// <para>创建日期:2017-07-24 </para>
///// <para>修改人:</para>
///// <para>修改日期:</para>
///// <para>修改备注:</para>
///// <para>版本:1.0</para>
///// </summary>
///// <param name="cmdType">语句类型存储过程或者sql语句</param>
///// <param name="cmdText">执行内容</param>
///// <param name="tabName">表名</param>
///// <param name="commandParameters">参数</param>
///// <returns>DataSet.</returns>
public static DataSet ExecuteDataSet(CommandType cmdType, string cmdText, string tabName, params SqlParameter[] commandParameters)
{
DataSet set2;
OdbcCommand cmd = new OdbcCommand();
try
{
PrepareCommand(cmd, _connection, null, cmdType, cmdText, commandParameters);
OdbcDataAdapter adapter = new OdbcDataAdapter(cmd);
DataSet dataSet = new DataSet();
adapter.Fill(dataSet, tabName);
//adapter.FillSchema(dataSet, SchemaType.Mapped, tabName);
set2 = dataSet;
}
catch (Exception e)
{
if (e.Message.StartsWith("在从服务器接收结果时发生传输级错误") ||
e.Message.StartsWith("在与 SQL Server 建立连接时出现与网络相关的或特定于实例的错误") ||
e.Message.StartsWith("在向服务器发送请求时发生传输级错误"))
{
throw new Exception("无法连接服务器,请检查网络连接.");
}
else
{
throw;
}
}
finally
{
cmd.Dispose();
}
return set2;
}
///// <summary>
///// <para>说明:查询结果集</para>
///// <para>创建人:龚宇超</para>
///// <para>创建日期:2017-07-24 </para>
///// <para>修改人:</para>
///// <para>修改日期:</para>
///// <para>修改备注:</para>
///// <para>版本:1.0</para>
///// </summary>
///// <param name="cmdType">语句类型存储过程或者sql语句</param>
///// <param name="cmdText">执行内容</param>
///// <param name="tabName">表名</param>
///// <returns>DataSet.</returns>
public static DataSet ExecuteDataSet(CommandType cmdType, string cmdText, string tabName)
{
return ExecuteDataSet(cmdType, cmdText, tabName, null);
}
///// <summary>
///// <para>说明:查询结果集</para>
///// <para>创建人:龚宇超</para>
///// <para>创建日期:2017-07-24 </para>
///// <para>修改人:</para>
///// <para>修改日期:</para>
///// <para>修改备注:</para>
///// <para>版本:1.0</para>
///// </summary>
///// <param name="cmdText">执行内容</param>
///// <returns>DataSet.</returns>
public static DataSet ExecuteDataSet(string cmdText)
{
return ExecuteDataSet(CommandType.Text, cmdText, "temp");
}
///// <summary>
///// <para>说明:查询结果集</para>
///// <para>创建人:龚宇超</para>
///// <para>创建日期:2017-07-24 </para>
///// <para>修改人:</para>
///// <para>修改日期:</para>
///// <para>修改备注:</para>
///// <para>版本:1.0</para>
///// </summary>
///// <param name="procedureName">Name of the procedure.</param>
///// <param name="tabName">表名</param>
///// <param name="parameterNames">The parameter names.</param>
///// <param name="parameterValues">The parameter values.</param>
///// <returns>DataSet.</returns>
//public static DataSet ExecuteDataSet(string procedureName, string tabName, string[] parameterNames, object[] parameterValues)
//{
// DataSet set2;
// try
// {
// OdbcCommand cmd = new OdbcCommand(procedureName, _connection);
// cmd.CommandType = CommandType.StoredProcedure;
// if (parameterNames != null && parameterValues != null)
// {
// for (int i = 0; i < parameterNames.Length && i < parameterValues.Length; i++)
// {
// cmd.Parameters.AddWithValue(parameterNames[i], parameterValues[i]);
// }
// }
// OdbcDataAdapter adapter = new OdbcDataAdapter(cmd);
// DataSet dataSet = new DataSet();
// adapter.Fill(dataSet, tabName);
// set2 = dataSet;
// }
// catch
// {
// throw;
// }
// return set2;
//}
//#endregion
#region ExecuteNonQuery
/// <summary>
/// <para>说明:执行sql语句或者存储过程</para>
/// <para>创建人:龚宇超</para>
/// <para>创建日期:2017-07-24 </para>
/// <para>修改人:</para>
/// <para>修改日期:</para>
/// <para>修改备注:</para>
/// <para>版本:1.0</para>
/// </summary>
/// <param name="cmdType">Type of the command.</param>
/// <param name="cmdText">The command text.</param>
/// <param name="commandParameters">The command parameters.</param>
/// <returns>System.Int32.</returns>
public static int ExecuteNonQuery(CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{
OdbcCommand cmd = new OdbcCommand();
int num = 0;
try
{
PrepareCommand(cmd, _connection, null, cmdType, cmdText, commandParameters);
num = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
}
catch (Exception e)
{
if (e.Message.StartsWith("在从服务器接收结果时发生传输级错误") ||
e.Message.StartsWith("在与 SQL Server 建立连接时出现与网络相关的或特定于实例的错误") ||
e.Message.StartsWith("在向服务器发送请求时发生传输级错误"))
{
throw new Exception("无法连接服务器,请检查网络连接.");
}
else
{
throw;
}
}
finally
{
cmd.Dispose();
}
return num;
}
/// <summary>
/// <para>说明:执行sql语句或者存储过程</para>
/// <para>创建人:龚宇超</para>
/// <para>创建日期:2017-07-24 </para>
/// <para>修改人:</para>
/// <para>修改日期:</para>
/// <para>修改备注:</para>
/// <para>版本:1.0</para>
/// </summary>
/// <param name="cmdType">Type of the command.</param>
/// <param name="cmdText">The command text.</param>
/// <returns>System.Int32.</returns>
public static int ExecuteNonQuery(CommandType cmdType, string cmdText)
{
return ExecuteNonQuery(CommandType.Text, cmdText, null);
}
/// <summary>
/// <para>说明:执行sql语句或者存储过程</para>
/// <para>创建人:龚宇超</para>
/// <para>创建日期:2017-07-24 </para>
/// <para>修改人:</para>
/// <para>修改日期:</para>
/// <para>修改备注:</para>
/// <para>版本:1.0</para>
/// </summary>
/// <param name="cmdText">The command text.</param>
/// <returns>System.Int32.</returns>
public static int ExecuteNonQuery(string cmdText)
{
return ExecuteNonQuery(CommandType.Text, cmdText);
}
#endregion
//#region ExecuteReader
///// <summary>
///// <para>说明:执行sql语句或者存储过程并返回结果集(只读、只进)</para>
///// <para>创建人:龚宇超</para>
///// <para>创建日期:2017-07-24 </para>
///// <para>修改人:</para>
///// <para>修改日期:</para>
///// <para>修改备注:</para>
///// <para>版本:1.0</para>
///// </summary>
///// <param name="cmdType">Type of the command.</param>
///// <param name="cmdText">The command text.</param>
///// <param name="commandParameters">The command parameters.</param>
///// <returns>SqlDataReader.</returns>
//public static OdbcDataReader ExecuteReader(CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
//{
// OdbcDataReader reader2;
// OdbcCommand cmd = new OdbcCommand();
// try
// {
// PrepareCommand(cmd, _connection, null, cmdType, cmdText, commandParameters);
// OdbcDataReader reader = cmd.ExecuteReader();
// cmd.Parameters.Clear();
// reader2 = reader;
// }
// catch
// {
// throw;
// }
// return reader2;
//}
//#endregion
//#region ExecuteScalar
///// <summary>
///// <para>说明:执行sql语句或者存储过程并返回结果集第一行第一列</para>
///// <para>创建人:龚宇超</para>
///// <para>创建日期:2017-07-24 </para>
///// <para>修改人:</para>
///// <para>修改日期:</para>
///// <para>修改备注:</para>
///// <para>版本:1.0</para>
///// </summary>
///// <param name="Connectionection">The connectionection.</param>
///// <param name="cmdType">Type of the command.</param>
///// <param name="cmdText">The command text.</param>
///// <param name="commandParameters">The command parameters.</param>
///// <returns>System.Object.</returns>
//public static object ExecuteScalar(OdbcConnection Connectionection, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
//{
// OdbcCommand cmd = new OdbcCommand();
// PrepareCommand(cmd, Connectionection, null, cmdType, cmdText, commandParameters);
// object obj2 = cmd.ExecuteScalar();
// cmd.Parameters.Clear();
// return obj2;
//}
///// <summary>
///// <para>说明:执行sql语句或者存储过程并返回结果集第一行第一列</para>
///// <para>创建人:龚宇超</para>
///// <para>创建日期:2017-07-24 </para>
///// <para>修改人:</para>
///// <para>修改日期:</para>
///// <para>修改备注:</para>
///// <para>版本:1.0</para>
///// </summary>
///// <param name="cmdType">Type of the command.</param>
///// <param name="cmdText">The command text.</param>
///// <param name="commandParameters">The command parameters.</param>
///// <returns>System.Object.</returns>
//public static object ExecuteScalar(CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
//{
// OdbcCommand cmd = new OdbcCommand();
// {
// PrepareCommand(cmd, _connection, null, cmdType, cmdText, commandParameters);
// object obj2 = cmd.ExecuteScalar();
// cmd.Parameters.Clear();
// return obj2;
// }
//}
///// <summary>
///// <para>说明:执行sql语句或者存储过程并返回结果集第一行第一列</para>
///// <para>创建人:龚宇超</para>
///// <para>创建日期:2017-07-24 </para>
///// <para>修改人:</para>
///// <para>修改日期:</para>
///// <para>修改备注:</para>
///// <para>版本:1.0</para>
///// </summary>
///// <param name="cmdType">Type of the command.</param>
///// <param name="cmdText">The command text.</param>
///// <returns>System.Object.</returns>
//public static object ExecuteScalar(CommandType cmdType, string cmdText)
//{
// OdbcCommand cmd = new OdbcCommand();
// {
// PrepareCommand(cmd, _connection, null, cmdType, cmdText, null);
// object obj2 = cmd.ExecuteScalar();
// cmd.Parameters.Clear();
// return obj2;
// }
//}
///// <summary>
///// <para>说明:执行sql语句或者存储过程并返回结果集第一行第一列</para>
///// <para>创建人:龚宇超</para>
///// <para>创建日期:2017-08-21 </para>
///// <para>修改人:</para>
///// <para>修改日期:</para>
///// <para>修改备注:</para>
///// <para>版本:1.0</para>
///// </summary>
///// <param name="cmdText">The command text.</param>
///// <returns>System.Object.</returns>
//public static object ExecuteScalar(string cmdText)
//{
// OdbcCommand cmd = new OdbcCommand();
// {
// PrepareCommand(cmd, _connection, null, CommandType.Text, cmdText, null);
// object obj2 = cmd.ExecuteScalar();
// cmd.Parameters.Clear();
// return obj2;
// }
//}
//#endregion
#region PrepareCommand
/// <summary>
/// <para>说明: sql参数处理</para>
/// <para>创建人:龚宇超</para>
/// <para>创建日期:2017-07-24 </para>
/// <para>修改人:</para>
/// <para>修改日期:</para>
/// <para>修改备注:</para>
/// <para>版本:1.0</para>
/// </summary>
/// <param name="cmd">The command.</param>
/// <param name="Connection">The connection.</param>
/// <param name="trans">The trans.</param>
/// <param name="cmdType">Type of the command.</param>
/// <param name="cmdText">The command text.</param>
/// <param name="cmdParms">The command parms.</param>
private static void PrepareCommand(OdbcCommand cmd, OdbcConnection Connection, OdbcTransaction trans, CommandType cmdType, string cmdText, SqlParameter[] cmdParms)
{
if (Connection.State != ConnectionState.Open)
{
Connection.Open();
}
cmd.Connection = Connection;
cmd.CommandTimeout = CommandTimeout;
cmd.CommandText = cmdText;
if (trans != null)
{
cmd.Transaction = trans;
}
cmd.CommandType = cmdType;
if (cmdParms != null)
{
foreach (SqlParameter parameter in cmdParms)
{
cmd.Parameters.Add(parameter);
}
}
}
#endregion
}
}
+21
View File
@@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace Lskj.TxtFileRead
{
static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new FrmMain());
}
}
}
@@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的常规信息通过以下
// 特性集控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("Lskj.TxtFileRead")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Lskj.TxtFileRead")]
[assembly: AssemblyCopyright("Copyright © 2020")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 使此程序集中的类型
// 对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型,
// 则将该类型上的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("960e0866-89d1-48f6-8906-7f56e10ea36a")]
// 程序集的版本信息由下面四个值组成:
//
// 主版本
// 次版本
// 内部版本号
// 修订号
//
// 可以指定所有这些值,也可以使用“内部版本号”和“修订号”的默认值,
// 方法是按如下所示使用“*”:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
@@ -0,0 +1,63 @@
//------------------------------------------------------------------------------
// <auto-generated>
// 此代码由工具生成。
// 运行时版本:4.0.30319.42000
//
// 对此文件的更改可能会导致不正确的行为,并且如果
// 重新生成代码,这些更改将会丢失。
// </auto-generated>
//------------------------------------------------------------------------------
namespace Lskj.TxtFileRead.Properties {
using System;
/// <summary>
/// 一个强类型的资源类,用于查找本地化的字符串等。
/// </summary>
// 此类是由 StronglyTypedResourceBuilder
// 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。
// 若要添加或移除成员,请编辑 .ResX 文件,然后重新运行 ResGen
// (以 /str 作为命令选项),或重新生成 VS 项目。
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// 返回此类使用的缓存的 ResourceManager 实例。
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Lskj.TxtFileRead.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// 使用此强类型资源类,为所有资源查找
/// 重写当前线程的 CurrentUICulture 属性。
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
}
}
@@ -0,0 +1,117 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>
@@ -0,0 +1,26 @@
//------------------------------------------------------------------------------
// <auto-generated>
// 此代码由工具生成。
// 运行时版本:4.0.30319.42000
//
// 对此文件的更改可能会导致不正确的行为,并且如果
// 重新生成代码,这些更改将会丢失。
// </auto-generated>
//------------------------------------------------------------------------------
namespace Lskj.TxtFileRead.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "10.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
}
}
@@ -0,0 +1,7 @@
<?xml version='1.0' encoding='utf-8'?>
<SettingsFile xmlns="http://schemas.microsoft.com/VisualStudio/2004/01/settings" CurrentProfile="(Default)">
<Profiles>
<Profile Name="(Default)" />
</Profiles>
<Settings />
</SettingsFile>
+230
View File
@@ -0,0 +1,230 @@
/******************************
* 说明:程序通用方法管理类
* 创建人:龚宇超
* 创建日期:2017-08-16
* 修改人:
* 修改日期:
* 修改备注:
* 版本:1.0.0.0
******************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace Lskj.TxtFileRead
{
/// <summary>
/// 程序通用方法管理类
/// </summary>
public sealed class PubUtil
{
/// <summary>
/// <para>说明:获取应用程序启动目录</para>
/// <para>创建人:龚宇超</para>
/// <para>创建日期:2017-08-21 </para>
/// <para>修改人:</para>
/// <para>修改日期:</para>
/// <para>修改备注:</para>
/// <para>版本:1.0</para>
/// </summary>
/// <returns>System.String.</returns>
public static string AbsolutelyPath
{
get { return Application.StartupPath + "\\"; }
}
/// <summary>
/// 获取应用程序启动目录下的Lib目录
/// </summary>
/// <value>The absolutely library path.</value>
public static string AbsolutelyLibPath
{
get { return AbsolutelyPath + "Lib/"; }
}
/// <summary>
/// 获取应用程序启动目录下的Browser目录
/// </summary>
/// <value>The absolutely browser path.</value>
public static string AbsolutelyBrowserPath
{
get { return AbsolutelyPath + "Browser/"; }
}
/// <summary>
/// 获取应用程序启动目录下的小平台目录
/// </summary>
/// <value>The absolutely small client path.</value>
public static string AbsolutelySmallClientPath
{
get { return AbsolutelyPath + "Client.exe"; }
}
/// <summary>
/// <para>说明:获取附件下载存放临时目录</para>
/// <para>创建人:龚宇超</para>
/// <para>创建日期:2017-11-01 </para>
/// <para>修改人:</para>
/// <para>修改日期:</para>
/// <para>修改备注:</para>
/// <para>版本:1.0</para>
/// </summary>
/// <returns>System.String.</returns>
public static string FileDownLoadTempPath
{
get
{
string path = AbsolutelyPath + "TempFiles/";
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
return path;
}
}
/// <summary>
/// 获取打印文件路径
/// </summary>
/// <value>The print file absolutely path.</value>
public static string PrintFileAbsolutelyPath
{
get { return AbsolutelyPath + "Lib/P_PubPrint.lsp"; }
}
/// <summary>
/// 获取新版打印文件路径
/// </summary>
/// <value>The print file absolutely path.</value>
public static string PrintFileAbsolutelyPath70
{
get { return AbsolutelyPath + "Lib/p_pubprint70.lsp"; }
}
/// <summary>
/// 附件exe文件路径
/// </summary>
/// <value>The name of the file executable.</value>
public static string AbsolutelyFileUploadPath
{
get { return AbsolutelyPath + "Attach/LSTest.exe"; }
}
/// <summary>
/// 主界面模块图片加载路径
/// </summary>
/// <value>The main menu default image.</value>
public static string MainMenuDefaultImage
{
get { return BitMapPath + "Main/Module/"; }
}
public static string MesItemImage
{
get { return BitMapPath + "MesItem/"; }
}
/// <summary>
/// 主界面、登录界面、子系统图片存放位置
/// </summary>
/// <value>The bit map path.</value>
public static string BitMapPath
{
get { return AbsolutelyPath + "Images/"; }
}
/// <summary>
/// 身份证阅读器图片存放位置
/// </summary>
/// <value>The identifier card bit map path.</value>
public static string IDCardBitMapPath
{
get
{
string filePath = AbsolutelyPath + "Card\\";
if (!Directory.Exists(filePath))
Directory.CreateDirectory(filePath);
return filePath;
}
}
/// <summary>
/// 串口通过ini本地设置
/// </summary>
/// <value>The main menu configuration path.</value>
public static string TextPath
{
get { return AbsolutelyPath + "text.ini"; }
}
/// <summary>
/// 模块配置文件存放路径
/// </summary>
/// <value>The main menu configuration path.</value>
public static string MainMenuConfigPath
{
get { return AbsolutelyPath + "MenuConfig.ini"; }
}
/// <summary>
/// 控件缓存数据源
/// </summary>
/// <value>The identifier card bit map path.</value>
public static string ControlCacheData
{
get
{
string filePath = AbsolutelyPath + "ControlData\\";
if (!Directory.Exists(filePath))
Directory.CreateDirectory(filePath);
return filePath;
}
}
/// <summary>
/// Excel模板路径
/// </summary>
/// <value>The menu excel path.</value>
public static string MenuExcelPath
{
get
{
string filePath = AbsolutelyPath + "Templete/";
if (!Directory.Exists(filePath))
{
Directory.CreateDirectory(filePath);
}
return filePath;
}
}
/// <summary>
/// 打印模板 repx文件存放地址
/// </summary>
public static string PrintModePath
{
get
{
string filePath = AbsolutelyPath + "Reports\\";
if (!Directory.Exists(filePath))
{
Directory.CreateDirectory(filePath);
}
return filePath;
}
}
/// <summary>
/// 打印模板语言包存放位置
/// </summary>
public static string PrintModeResourcePath
{
get
{
return AbsolutelyPath + "Localization\\Chinese (Simplified).frl";
}
}
/// <summary>
/// 软件升级日志
/// </summary>
/// <value>The system update log path.</value>
public static string SystemUpdateLogPath
{
get { return AbsolutelyPath + "\\Log.txt"; }
}
/// <summary>
/// WebView2
/// </summary>
/// <value>The system update log path.</value>
public static string WebViewPath
{
get { return AbsolutelyPath + "\\Browser2\\"; }
}
}
}
+605
View File
@@ -0,0 +1,605 @@
/******************************
* 说明:数据库操作类
* 创建人:龚宇超
* 创建日期:2017-07-24
* 修改人:
* 修改日期:
* 修改备注:
* 版本:1.0.0.0
******************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
namespace Lskj.Core
{
/// <summary>
/// 数据库操作类
/// </summary>
public static class SqlHelper
{
/// <summary>
/// 数据连接
/// </summary>
public static SqlConnection _connection;
/// <summary>
/// 请求超时时间
/// </summary>
public static int CommandTimeout;
#region ExecuteAdapter
/// <summary>
/// <para>说明:获取适配器</para>
/// <para>创建人:龚宇超</para>
/// <para>创建日期:2017-07-24 </para>
/// <para>修改人:</para>
/// <para>修改日期:</para>
/// <para>修改备注:</para>
/// <para>版本:1.0</para>
/// </summary>
/// <param name="cmdType">Type of the command.</param>
/// <param name="cmdText">The command text.</param>
/// <param name="commandParameters">The command parameters.</param>
/// <returns>SqlDataAdapter.</returns>
public static SqlDataAdapter ExecuteAdapter(CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{
SqlDataAdapter adapter;
SqlCommand cmd = new SqlCommand();
try
{
PrepareCommand(cmd, _connection, null, cmdType, cmdText, commandParameters);
adapter = new SqlDataAdapter(cmd);
}
catch
{
throw;
}
return adapter;
}
/// <summary>
/// <para>说明:获取适配器</para>
/// <para>创建人:龚宇超</para>
/// <para>创建日期:2017-07-24 </para>
/// <para>修改人:</para>
/// <para>修改日期:</para>
/// <para>修改备注:</para>
/// <para>版本:1.0</para>
/// </summary>
/// <param name="cmdType">Type of the command.</param>
/// <param name="cmdText">The command text.</param>
/// <returns>SqlDataAdapter.</returns>
public static SqlDataAdapter ExecuteAdapter(CommandType cmdType, string cmdText)
{
SqlDataAdapter adapter;
SqlCommand cmd = new SqlCommand();
try
{
PrepareCommand(cmd, _connection, null, cmdType, cmdText, null);
adapter = new SqlDataAdapter(cmd);
}
catch
{
throw;
}
return adapter;
}
#endregion
#region ExecuteDataTable
/// <summary>
/// <para>说明:执行sql返回DataTable</para>
/// <para>创建人:龚宇超</para>
/// <para>创建日期:2017-07-24 </para>
/// <para>修改人:</para>
/// <para>修改日期:</para>
/// <para>修改备注:</para>
/// <para>版本:1.0</para>
/// </summary>
/// <param name="cmdText">The command text.</param>
/// <returns>DataTable.</returns>
public static DataTable ExecuteDataTable(string cmdText)
{
return ExecuteDataSet(cmdText).Tables[0];
}
/// <summary>
/// <para>说明:执行sql返回DataTable</para>
/// <para>创建人:龚宇超</para>
/// <para>创建日期:2017-07-24 </para>
/// <para>修改人:</para>
/// <para>修改日期:</para>
/// <para>修改备注:</para>
/// <para>版本:1.0</para>
/// </summary>
/// <param name="cmdText">The command text.</param>
/// <returns>DataTable.</returns>
public static DataTable ExecuteDataTable(string cmdText, params SqlParameter[] commandParameters)
{
return ExecuteDataSet(CommandType.Text, cmdText, "temp", commandParameters).Tables[0];
}
/// <summary>
/// <para>说明:执行sql返回指定字段值</para>
/// <para>创建人:龚宇超</para>
/// <para>创建日期:2017-08-15 </para>
/// <para>修改人:</para>
/// <para>修改日期:</para>
/// <para>修改备注:</para>
/// <para>版本:1.0</para>
/// </summary>
/// <param name="fieldName">Name of the field.</param>
/// <param name="cmdText">The command text.</param>
/// <returns>System.Object.</returns>
public static object ExecuteObject(string fieldName, string cmdText)
{
object result = null;
try
{
result = ExecuteDataSet(cmdText).Tables[0].Rows[0][fieldName];
}
catch (Exception)
{
}
return result;
}
/// <summary>
/// <para>说明:执行sql返回指定字段值</para>
/// <para>创建人:龚宇超</para>
/// <para>创建日期:2017-11-27 </para>
/// <para>修改人:</para>
/// <para>修改日期:</para>
/// <para>修改备注:</para>
/// <para>版本:1.0</para>
/// </summary>
/// <param name="fieldName">Name of the field.</param>
/// <param name="cmdText">The command text.</param>
/// <param name="commandParameters">The command parameters.</param>
/// <returns>System.Object.</returns>
public static object ExecuteObject(string fieldName, string cmdText, params SqlParameter[] commandParameters)
{
object result = null;
try
{
result = ExecuteDataSet(CommandType.Text, cmdText, "temp", commandParameters).Tables[0].Rows[0][fieldName];
}
catch (Exception)
{
}
return result;
}
/// <summary>
/// <para>说明:执行sql返回指定字段值</para>
/// <para>创建人:龚宇超</para>
/// <para>创建日期:2017-08-15 </para>
/// <para>修改人:</para>
/// <para>修改日期:</para>
/// <para>修改备注:</para>
/// <para>版本:1.0</para>
/// </summary>
/// <param name="fieldName">Name of the field.</param>
/// <param name="cmdText">The command text.</param>
/// <returns>System.Object.</returns>
public static string ExecuteString(string fieldName, string cmdText)
{
object obj = ExecuteObject(fieldName, cmdText);
return obj == null ? "" : obj.ToString();
}
/// <summary>
/// <para>说明:执行sql返回指定字段值</para>
/// <para>创建人:龚宇超</para>
/// <para>创建日期:2017-11-27 </para>
/// <para>修改人:</para>
/// <para>修改日期:</para>
/// <para>修改备注:</para>
/// <para>版本:1.0</para>
/// </summary>
/// <param name="fieldName">Name of the field.</param>
/// <param name="cmdText">The command text.</param>
/// <param name="commandParameters">The command parameters.</param>
/// <returns>System.String.</returns>
public static string ExecuteString(string fieldName, string cmdText, params SqlParameter[] commandParameters)
{
object obj = ExecuteObject(fieldName, cmdText, commandParameters);
return obj == null ? "" : obj.ToString();
}
#endregion
#region ExecuteDataSet
/// <summary>
/// <para>说明:查询结果集</para>
/// <para>创建人:龚宇超</para>
/// <para>创建日期:2017-07-24 </para>
/// <para>修改人:</para>
/// <para>修改日期:</para>
/// <para>修改备注:</para>
/// <para>版本:1.0</para>
/// </summary>
/// <param name="cmdType">Type of the command.</param>
/// <param name="cmdText">The command text.</param>
/// <param name="tabName">Name of the tab.</param>
/// <param name="commandParameters">The command parameters.</param>
/// <returns>DataSet.</returns>
public static DataSet ExecuteDataSet(int cmdType, string cmdText, string tabName, params SqlParameter[] commandParameters)
{
CommandType _cmdType = CommandType.Text;
switch (cmdType)
{
case 4:
_cmdType = CommandType.StoredProcedure;
break;
case 512:
_cmdType = CommandType.TableDirect;
break;
}
return ExecuteDataSet(_cmdType, cmdText, tabName, commandParameters);
}
/// <summary>
/// <para>说明:查询结果集</para>
/// <para>创建人:龚宇超</para>
/// <para>创建日期:2017-07-24 </para>
/// <para>修改人:</para>
/// <para>修改日期:</para>
/// <para>修改备注:</para>
/// <para>版本:1.0</para>
/// </summary>
/// <param name="cmdType">语句类型存储过程或者sql语句</param>
/// <param name="cmdText">执行内容</param>
/// <param name="tabName">表名</param>
/// <param name="commandParameters">参数</param>
/// <returns>DataSet.</returns>
public static DataSet ExecuteDataSet(CommandType cmdType, string cmdText, string tabName, params SqlParameter[] commandParameters)
{
DataSet set2;
SqlCommand cmd = new SqlCommand();
try
{
PrepareCommand(cmd, _connection, null, cmdType, cmdText, commandParameters);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet dataSet = new DataSet();
adapter.Fill(dataSet, tabName);
//adapter.FillSchema(dataSet, SchemaType.Mapped, tabName);
set2 = dataSet;
}
catch (Exception e)
{
if (e.Message.StartsWith("在从服务器接收结果时发生传输级错误") ||
e.Message.StartsWith("在与 SQL Server 建立连接时出现与网络相关的或特定于实例的错误") ||
e.Message.StartsWith("在向服务器发送请求时发生传输级错误"))
{
throw new Exception("无法连接服务器,请检查网络连接.");
}
else
{
throw;
}
}
finally
{
cmd.Dispose();
}
return set2;
}
/// <summary>
/// <para>说明:查询结果集</para>
/// <para>创建人:龚宇超</para>
/// <para>创建日期:2017-07-24 </para>
/// <para>修改人:</para>
/// <para>修改日期:</para>
/// <para>修改备注:</para>
/// <para>版本:1.0</para>
/// </summary>
/// <param name="cmdType">语句类型存储过程或者sql语句</param>
/// <param name="cmdText">执行内容</param>
/// <param name="tabName">表名</param>
/// <returns>DataSet.</returns>
public static DataSet ExecuteDataSet(CommandType cmdType, string cmdText, string tabName)
{
return ExecuteDataSet(cmdType, cmdText, tabName, null);
}
/// <summary>
/// <para>说明:查询结果集</para>
/// <para>创建人:龚宇超</para>
/// <para>创建日期:2017-07-24 </para>
/// <para>修改人:</para>
/// <para>修改日期:</para>
/// <para>修改备注:</para>
/// <para>版本:1.0</para>
/// </summary>
/// <param name="cmdText">执行内容</param>
/// <returns>DataSet.</returns>
public static DataSet ExecuteDataSet(string cmdText)
{
return ExecuteDataSet(CommandType.Text, cmdText, "temp");
}
/// <summary>
/// <para>说明:查询结果集</para>
/// <para>创建人:龚宇超</para>
/// <para>创建日期:2017-07-24 </para>
/// <para>修改人:</para>
/// <para>修改日期:</para>
/// <para>修改备注:</para>
/// <para>版本:1.0</para>
/// </summary>
/// <param name="procedureName">Name of the procedure.</param>
/// <param name="tabName">表名</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="parameterValues">The parameter values.</param>
/// <returns>DataSet.</returns>
public static DataSet ExecuteDataSet(string procedureName, string tabName, string[] parameterNames, object[] parameterValues)
{
DataSet set2;
try
{
SqlCommand cmd = new SqlCommand(procedureName, _connection);
cmd.CommandType = CommandType.StoredProcedure;
if (parameterNames != null && parameterValues != null)
{
for (int i = 0; i < parameterNames.Length && i < parameterValues.Length; i++)
{
cmd.Parameters.AddWithValue(parameterNames[i], parameterValues[i]);
}
}
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet dataSet = new DataSet();
adapter.Fill(dataSet, tabName);
set2 = dataSet;
}
catch
{
throw;
}
return set2;
}
#endregion
#region ExecuteNonQuery
/// <summary>
/// <para>说明:执行sql语句或者存储过程</para>
/// <para>创建人:龚宇超</para>
/// <para>创建日期:2017-07-24 </para>
/// <para>修改人:</para>
/// <para>修改日期:</para>
/// <para>修改备注:</para>
/// <para>版本:1.0</para>
/// </summary>
/// <param name="cmdType">Type of the command.</param>
/// <param name="cmdText">The command text.</param>
/// <param name="commandParameters">The command parameters.</param>
/// <returns>System.Int32.</returns>
public static int ExecuteNonQuery(CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{
SqlCommand cmd = new SqlCommand();
int num = 0;
try
{
PrepareCommand(cmd, _connection, null, cmdType, cmdText, commandParameters);
num = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
}
catch (Exception e)
{
if (e.Message.StartsWith("在从服务器接收结果时发生传输级错误") ||
e.Message.StartsWith("在与 SQL Server 建立连接时出现与网络相关的或特定于实例的错误") ||
e.Message.StartsWith("在向服务器发送请求时发生传输级错误"))
{
throw new Exception("无法连接服务器,请检查网络连接.");
}
else
{
throw;
}
}
finally
{
cmd.Dispose();
}
return num;
}
/// <summary>
/// <para>说明:执行sql语句或者存储过程</para>
/// <para>创建人:龚宇超</para>
/// <para>创建日期:2017-07-24 </para>
/// <para>修改人:</para>
/// <para>修改日期:</para>
/// <para>修改备注:</para>
/// <para>版本:1.0</para>
/// </summary>
/// <param name="cmdType">Type of the command.</param>
/// <param name="cmdText">The command text.</param>
/// <returns>System.Int32.</returns>
public static int ExecuteNonQuery(CommandType cmdType, string cmdText)
{
return ExecuteNonQuery(CommandType.Text, cmdText, null);
}
/// <summary>
/// <para>说明:执行sql语句或者存储过程</para>
/// <para>创建人:龚宇超</para>
/// <para>创建日期:2017-07-24 </para>
/// <para>修改人:</para>
/// <para>修改日期:</para>
/// <para>修改备注:</para>
/// <para>版本:1.0</para>
/// </summary>
/// <param name="cmdText">The command text.</param>
/// <returns>System.Int32.</returns>
public static int ExecuteNonQuery(string cmdText)
{
return ExecuteNonQuery(CommandType.Text, cmdText);
}
#endregion
#region ExecuteReader
/// <summary>
/// <para>说明:执行sql语句或者存储过程并返回结果集(只读、只进)</para>
/// <para>创建人:龚宇超</para>
/// <para>创建日期:2017-07-24 </para>
/// <para>修改人:</para>
/// <para>修改日期:</para>
/// <para>修改备注:</para>
/// <para>版本:1.0</para>
/// </summary>
/// <param name="cmdType">Type of the command.</param>
/// <param name="cmdText">The command text.</param>
/// <param name="commandParameters">The command parameters.</param>
/// <returns>SqlDataReader.</returns>
public static SqlDataReader ExecuteReader(CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{
SqlDataReader reader2;
SqlCommand cmd = new SqlCommand();
try
{
PrepareCommand(cmd, _connection, null, cmdType, cmdText, commandParameters);
SqlDataReader reader = cmd.ExecuteReader();
cmd.Parameters.Clear();
reader2 = reader;
}
catch
{
throw;
}
return reader2;
}
#endregion
#region ExecuteScalar
/// <summary>
/// <para>说明:执行sql语句或者存储过程并返回结果集第一行第一列</para>
/// <para>创建人:龚宇超</para>
/// <para>创建日期:2017-07-24 </para>
/// <para>修改人:</para>
/// <para>修改日期:</para>
/// <para>修改备注:</para>
/// <para>版本:1.0</para>
/// </summary>
/// <param name="Connectionection">The connectionection.</param>
/// <param name="cmdType">Type of the command.</param>
/// <param name="cmdText">The command text.</param>
/// <param name="commandParameters">The command parameters.</param>
/// <returns>System.Object.</returns>
public static object ExecuteScalar(SqlConnection Connectionection, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{
SqlCommand cmd = new SqlCommand();
PrepareCommand(cmd, Connectionection, null, cmdType, cmdText, commandParameters);
object obj2 = cmd.ExecuteScalar();
cmd.Parameters.Clear();
return obj2;
}
/// <summary>
/// <para>说明:执行sql语句或者存储过程并返回结果集第一行第一列</para>
/// <para>创建人:龚宇超</para>
/// <para>创建日期:2017-07-24 </para>
/// <para>修改人:</para>
/// <para>修改日期:</para>
/// <para>修改备注:</para>
/// <para>版本:1.0</para>
/// </summary>
/// <param name="cmdType">Type of the command.</param>
/// <param name="cmdText">The command text.</param>
/// <param name="commandParameters">The command parameters.</param>
/// <returns>System.Object.</returns>
public static object ExecuteScalar(CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{
SqlCommand cmd = new SqlCommand();
{
PrepareCommand(cmd, _connection, null, cmdType, cmdText, commandParameters);
object obj2 = cmd.ExecuteScalar();
cmd.Parameters.Clear();
return obj2;
}
}
/// <summary>
/// <para>说明:执行sql语句或者存储过程并返回结果集第一行第一列</para>
/// <para>创建人:龚宇超</para>
/// <para>创建日期:2017-07-24 </para>
/// <para>修改人:</para>
/// <para>修改日期:</para>
/// <para>修改备注:</para>
/// <para>版本:1.0</para>
/// </summary>
/// <param name="cmdType">Type of the command.</param>
/// <param name="cmdText">The command text.</param>
/// <returns>System.Object.</returns>
public static object ExecuteScalar(CommandType cmdType, string cmdText)
{
SqlCommand cmd = new SqlCommand();
{
PrepareCommand(cmd, _connection, null, cmdType, cmdText, null);
object obj2 = cmd.ExecuteScalar();
cmd.Parameters.Clear();
return obj2;
}
}
/// <summary>
/// <para>说明:执行sql语句或者存储过程并返回结果集第一行第一列</para>
/// <para>创建人:龚宇超</para>
/// <para>创建日期:2017-08-21 </para>
/// <para>修改人:</para>
/// <para>修改日期:</para>
/// <para>修改备注:</para>
/// <para>版本:1.0</para>
/// </summary>
/// <param name="cmdText">The command text.</param>
/// <returns>System.Object.</returns>
public static object ExecuteScalar(string cmdText)
{
SqlCommand cmd = new SqlCommand();
{
PrepareCommand(cmd, _connection, null, CommandType.Text, cmdText, null);
object obj2 = cmd.ExecuteScalar();
cmd.Parameters.Clear();
return obj2;
}
}
#endregion
#region PrepareCommand
/// <summary>
/// <para>说明: sql参数处理</para>
/// <para>创建人:龚宇超</para>
/// <para>创建日期:2017-07-24 </para>
/// <para>修改人:</para>
/// <para>修改日期:</para>
/// <para>修改备注:</para>
/// <para>版本:1.0</para>
/// </summary>
/// <param name="cmd">The command.</param>
/// <param name="Connection">The connection.</param>
/// <param name="trans">The trans.</param>
/// <param name="cmdType">Type of the command.</param>
/// <param name="cmdText">The command text.</param>
/// <param name="cmdParms">The command parms.</param>
private static void PrepareCommand(SqlCommand cmd, SqlConnection Connection, SqlTransaction trans, CommandType cmdType, string cmdText, SqlParameter[] cmdParms)
{
if (Connection.State != ConnectionState.Open)
{
Connection.Open();
}
cmd.Connection = Connection;
cmd.CommandTimeout = CommandTimeout;
cmd.CommandText = cmdText;
if (trans != null)
{
cmd.Transaction = trans;
}
cmd.CommandType = cmdType;
if (cmdParms != null)
{
foreach (SqlParameter parameter in cmdParms)
{
cmd.Parameters.Add(parameter);
}
}
}
#endregion
}
}
+3
View File
@@ -0,0 +1,3 @@
<?xml version="1.0"?>
<configuration>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/></startup></configuration>
Binary file not shown.

After

Width:  |  Height:  |  Size: 66 KiB