常用代码段集合
打印DataTable表数据 ( Archived on 2008-9-25 11:35:20 )
插入圖片到SQLite數據庫 ( Archived on 2008-9-24 17:26:24 )
test_webService.Service service = new test_webService.Service();
DataSet ds = service.GetEmployees();
string connstring = string.Format("Data Source={0};Version=3;", @"D:\cs\lj\dbbb.db");
//CREATE TABLE [Test] (
//[id] INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
//[image] Boob NULL
//)
string insertSql = "Insert Into [Test] ([image]) Values(@image)";
using (SQLiteConnection conn = new SQLiteConnection(connstring))
{
// 连接数据库
conn.Open();
SQLiteCommand cmd = conn.CreateCommand();
cmd.Connection = conn;
//DbTransaction trans = conn.BeginTransaction();
SQLiteTransaction trans = conn.BeginTransaction();
try
{
//保存數據
cmd.CommandText = insertSql;
// 添加参数
//cmd.Parameters.Add(cmd.CreateParameter());
cmd.Parameters.Add("image", DbType.Binary);
DataTable dt = ds.Tables[0];
foreach (DataRow dr in dt.Rows)
{
cmd.Parameters[0].Value = (byte[])(dr["Photo"]);
cmd.ExecuteNonQuery();
}
// <-------------------
trans.Commit();
}
catch (Exception ex)
{
trans.Rollback();
throw;
}
}
如何高效使用SQLite .net (C#) ( Archived on 2008-9-11 21:12:30 )
using System.Data;
using System.Data.Common;
using System.Data.SQLite;
// 创建数据库文件
File.Delete("test1.db3");
SQLiteConnection.CreateFile("test1.db3");
DbProviderFactory factory = SQLiteFactory.Instance;
using (DbConnection conn = factory.CreateConnection())
{
// 连接数据库
conn.ConnectionString = "Data Source=test1.db3";
conn.Open();
// 创建数据表
string sql = "create table [test1] ([id] INTEGER PRIMARY KEY, [s] TEXT COLLATE NOCASE)";
DbCommand cmd = conn.CreateCommand();
cmd.Connection = conn;
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
// 添加参数
cmd.Parameters.Add(cmd.CreateParameter());
// 开始计时
Stopwatch watch = new Stopwatch();
watch.Start();
DbTransaction trans = conn.BeginTransaction(); // <-------------------
try
{
// 连续插入1000条记录
for (int i = 0; i < 1000; i++)
{
cmd.CommandText = "insert into [test1] ([s]) values (?)";
cmd.Parameters[0].Value = i.ToString();
cmd.ExecuteNonQuery();
}
trans.Commit(); // <-------------------
}
catch
{
trans.Rollback(); // <-------------------
throw; // <-------------------
}
// 停止计时
watch.Stop();
Console.WriteLine(watch.Elapsed);
}
执行一下,耗时 0.2 秒
在PDA设备中怎么取得程序所在的路径 ( Archived on 2008-9-10 15:07:50 )
System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase
結果
"\\Program Files\\SmartDeviceProject1\\SmartDeviceProject1.exe"
WebService中重設SERVICE的地址 ( Archived on 2008-9-9 15:30:52 )
csoft_webService.Service service = new csoft_webService.Service();
service.Url = "http://www.csstsoft.com/WebService.asmx";
string s = service.HelloWorld();
在DATATABLE上添加一列并设置其每行数据 ( Archived on 2008-8-27 11:28:51 )
Database db = DatabaseFactory.CreateDatabase("SqlMainDbConnectionString");
string strSqlSelect = @"Select ent_id,event_sum_id,alert_remark_id, remark as CommentDes,cd,creater,alert_status_id end_reason,end_reason_id from t_ent_alert_remark order by cd asc";
DbCommand dbCommand = db.GetSqlStringCommand(strSqlSelect);
DataTable dt = db.ExecuteDataSet(dbCommand).Tables[0];
dt.Columns.Add("CommentTime", typeof(string));
//设置时间
int recordCount = dt.Rows.Count;
for (int i = 0; i < recordCount; i++)
{
DateTime dCommentTime = Convert.ToDateTime(dt.Rows[i]["cd"]);
dt.Rows[i]["CommentTime"] = string.Format("{0:yyyy-MM-dd hh:mm:ss}", dCommentTime);
}
return dt;
DataTable 修改数据 ( Archived on 2008-8-27 11:00:03 )
for (int i = 0; i < DataTable.Rows.Count; i++)
{
DataRow dt = DataTable.Rows[i];
dt.BeginEdit();
dt["Column"] = "value";
dt.EndEdit();
}
格式化DataTable表数据(生成表格形式字符串) ( Archived on 2008-8-21 11:55:03 )
/// <summary>
/// Formats the data table data.
/// </summary>
/// <param name="dt">The dt.</param>
/// <returns></returns>
public static string FormatDataTableData(DataTable dt)
{
StringBuilder sb = new StringBuilder();
sb.Append("<table border=\"1\">");
sb.Append("<tr>");
foreach (DataColumn dl in dt.Columns)
{
sb.Append(string.Format("<td>{0}</br>({1})</td>", dl.ColumnName, dl.DataType));
}
sb.Append("</tr>");
int j = 1;
foreach (DataRow dr in dt.Rows)
{
sb.Append("<tr>");
for (int i = 0; i < dt.Columns.Count; i++)
{
if (i == 0)
{
sb.Append(string.Format("<td> Row:{0} - {1} </td>", j, dr[i]));
}
else
{
sb.Append(string.Format("<td> {0} </td>", dr[i]));
}
}
sb.Append("</tr>");
j++;
}
sb.Append("</table>");
return sb.ToString();
}
格式化日期2 ( Archived on 2008-8-21 10:43:55 )
string strDate = string.Format("{0:yyyy-MM-dd hh:mm:ss}", DateTime.Now); //{0:yyyy-MM-dd HH24:mm:ss}
格式化日期 ( Archived on 2008-8-21 10:22:55 )
DateTime bTime = DateTime.Now;
newRow["Start"] = string.Format("{0}-{1}-{2} {3}:{4}:{5}", bTime.Year.ToString("000#"), bTime.Month.ToString("0#"), bTime.Day.ToString("0#"), bTime.Hour.ToString("0#"), bTime.Minute.ToString("0#"), bTime.Second.ToString("0#"), bTime.ToString());
--------------------
效果
2007-03-05 11:44:55
取配置节数据库连接信息 ( Archived on 2008-8-20 11:27:37 )
string connstring = string.Empty;
ConnectionStringSettings settings = ConfigurationManager.ConnectionStrings["DataBaseConnection"];
if (settings != null)
{
connstring = settings.ConnectionString;
}
修改配置信息 ( Archived on 2008-8-20 11:26:58 )
public void SaveConfig(string key, string value)
{
try
{
string fileName = "Web.Config";
XmlDocument document = new XmlDocument();
document.Load(fileName);
((XmlElement)document.SelectSingleNode(@"//AppSetting/add[@key='" + key + "']")).SetAttribute("Value", value);
document.Save(fileName);
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
发送邮件 ( Archived on 2008-8-14 18:11:18 )
using System;
using System.Web;
using System.Web.Mail;
public class TestSendMail
{
public static void Main()
{
try
{
// Construct a new mail message
MailMessage message = new MailMessage();
message.From = from@domain.com;
message.To = chenaspx@qq.com;
message.Cc = ;
message.Bcc = ;
message.Subject = Subject;
message.Body = Content of message;
//if you want attach file with this mail, add the line below
message.Attachments.Add(new MailAttachment(c:\\attach.txt, MailEncoding.Base64));
// Send the message
SmtpMail.Send(message);
System.Console.WriteLine(Message has been sent);
}
catch(Exception ex)
{
System.Console.WriteLine(ex.Message.ToString());
}
}
}
绑定系统进程 ( Archived on 2008-8-14 18:07:52 )
private void BindProcess()
{
try
{
System.Diagnostics.Process[] ps = System.Diagnostics.Process.GetProcesses();
foreach (System.Diagnostics.Process p in ps)
{
//“System”与“Idle”进程没有关联进程的模块,所以不能过去模块的完整路径
if (p.ProcessName.ToLower() != "system" && p.ProcessName.ToLower() != "idle")
{
//进程名,物理内存,路径
this.listBox1.Items.Add(p.ProcessName + "\t" + p.WorkingSet64.ToString() + "\t" + p.MainModule.FileName);
}
else
{
//进程名,物理内存
this.listBox1.Items.Add(p.ProcessName + "\t" + p.WorkingSet64.ToString());
}
Text = "进程总数:" + ps.Length.ToString();
}
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
}
关闭系统服务 ( Archived on 2008-8-14 18:07:13 )
//关闭系统服务,需要引用命名空间:System.ServiceProcess
private void StopService(string serveceName)
{
try
{
System.ServiceProcess.ServiceController sc = new System.ServiceProcess.ServiceController(serveceName);
if (sc.Status == System.ServiceProcess.ServiceControllerStatus.Running)
{
sc.Stop();
}
}
catch(Exception exc)
{
MessageBox.Show(exc.Message);
}
}
打开文本文件 ( Archived on 2008-8-14 18:05:47 )
//打开文本文件
private void OpenNotepad()
{
//声明一个程序信息类
System.Diagnostics.ProcessStartInfo Info = new System.Diagnostics.ProcessStartInfo();
//设置外部程序名
Info.FileName = "notepad.exe";
//设置外部程序的启动参数(命令行参数)为test.txt
Info.Arguments = "test.txt";
//设置外部程序工作目录为 C:\
Info.WorkingDirectory = "C:\\";
//声明一个程序类
System.Diagnostics.Process Proc;
try
{
//启动外部程序
Proc = System.Diagnostics.Process.Start(Info);
}
catch (System.ComponentModel.Win32Exception exc)
{
MessageBox.Show("系统找不到指定的程序文件。\r{0}", exc.Message);
}
}
获取系统文件夹 ( Archived on 2008-8-14 18:03:59 )
//获取系统文件夹
string folder = System.Environment.GetFolderPath(Environment.SpecialFolder.System);
判断一字符串是否全为数字 ( Archived on 2008-8-14 17:54:33 )
public static bool IsInteger(string strIn)
{
if (strIn == "")
{
return false;
}
foreach (char Char in strIn)
{
if (!char.IsNumber(Char))
{
return false;
}
}
return true;
}
C#中实现文件拖放打开 ( Archived on 2008-8-14 17:06:03 )
将该控件的 AllowDrop 属性更改为 True,以允许将对象拖到控件上
private void Form1_DragEnter(object sender, System.Windows.Forms.DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
e.Effect = DragDropEffects.Link;
else e.Effect = DragDropEffects.None;
}
private void Form1_DragDrop(object sender, System.Windows.Forms.DragEventArgs e)
{
//其中label1.Text显示的就是拖进文件的文件名;
label1.Text = ((System.Array)e.Data.GetData(DataFormats.FileDrop)).GetValue(0).ToString();
}
显示指定图片到pictureBox控件 ( Archived on 2008-8-14 16:48:38 )
using System.IO;
using System.Drawing;
string imgFile = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "aboutCSST.jpg");
try
{
Image img = Image.FromFile(imgFile);
this.pictureBoxAbout.Image = img;
}
catch (Exception ex)
{
LogMsg.WriteLogToApplicationFolderByMonth(ex.ToString());
}
SQLite数据库操作 ( Archived on 2008-8-14 15:46:08 )
public DataSet ExecuteDataSet(string sql, string connectionString)
{
using (SQLiteConnection connection = new SQLiteConnection(connectionString))
{
connection.Open();
DataSet ds = new DataSet();
SQLiteDataAdapter da = new SQLiteDataAdapter(sql, connectionString);
da.Fill(ds);
return ds;
}
}
public int ExecuteNonQuery(string sql, string connectionString)
{
using (SQLiteConnection connection = new SQLiteConnection(connectionString))
{
connection.Open();
SQLiteCommand cmd = new SQLiteCommand(sql, connection);
return cmd.ExecuteNonQuery();
}
}
public object ExecuteScalar(string sql, string connectionString)
{
using (SQLiteConnection connection = new SQLiteConnection(connectionString))
{
connection.Open();
SQLiteCommand cmd = new SQLiteCommand(sql, connection);
return cmd.ExecuteScalar();
}
}
提取动态网页内容 ( Archived on 2008-8-14 11:28:32 )
Uri uri = new Uri("http://www.csstsoft.com/");
WebRequest req = WebRequest.Create(uri);
WebResponse resp = req.GetResponse();
Stream str = resp.GetResponseStream();
StreamReader sr = new StreamReader(str,System.Text.Encoding.Default);
string t = sr.ReadToEnd();
this.Response.Write(t.ToString());
MD5加密(Hash) ( Archived on 2008-8-14 10:11:50 )
public static string ConvertStringToMD5Hash(string str)
{
byte[] ByteToHash = (new System.Text.UnicodeEncoding()).GetBytes(str);
byte[] HashValue = ((System.Security.Cryptography.HashAlgorithm)System.Security.Cryptography.CryptoConfig.CreateFromName("MD5")).ComputeHash(ByteToHash);
return System.BitConverter.ToString(HashValue);
}
记录日志到应用程序目录 ( Archived on 2008-8-14 9:59:43 )
public static void LogMessageToApplicatonFolder(string msg)
{
string folder = string.Format(@"{0}\Log_{1}.log", System.Windows.Forms.Application.StartupPath,System.DateTime.Now.ToString("yyyy_MM"));
msg = string.Format("\r\n--------------------------{0}-------------------------\r\n{1}", System.DateTime.Now, msg);
System.IO.File.AppendAllText(folder,msg,System.Text.Encoding.UTF8);
}
在字符串左边添加N个字符(如在数字前补0) ( Archived on 2008-8-14 9:43:41 )
private static string AddCharToLeft(string originalString, char chr,int length)
{
if (originalString.Length > length) return originalString;//throw new ArgumentException();
return new string(chr, length - originalString.Length) + originalString;
}