C# 常用代码片段
一、从控制台读取东西代码片断:
using System; class TestReadConsole
{
public static void Main()
{
Console.Write(Enter your name:);
string strName = Console.ReadLine();
Console.WriteLine( Hi + strName);
}
}
二、读文件代码片断:
using System;
using System.IO; public class TestReadFile
{
public static void Main(String[] args)
{
// Read text file C:\temp\test.txt
FileStream fs = new FileStream(@c:\temp\test.txt , FileMode.Open, FileAccess.Read);
StreamReader sr = new StreamReader(fs); String line=sr.ReadLine();
while (line!=null)
{
Console.WriteLine(line);
line=sr.ReadLine();
} sr.Close();
fs.Close();
}
}
三、写文件代码:
using System;
using System.IO; public class TestWriteFile
{
public static void Main(String[] args)
{
// Create a text file C:\temp\test.txt
FileStream fs = new FileStream(@c:\temp\test.txt , FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs);
// Write to the file using StreamWriter class
sw.BaseStream.Seek(0, SeekOrigin.End);
sw.WriteLine( First Line );
sw.WriteLine( Second Line);
sw.Flush();
}
}
四、拷贝文件:
using System;
using System.IO; class TestCopyFile
{
public static void Main()
{
File.Copy(c:\\temp\\source.txt, C:\\temp\\dest.txt );
}
}
五、移动文件:
using System;
using System.IO; class TestMoveFile
{
public static void Main()
{
File.Move(c:\\temp\\abc.txt, C:\\temp\\def.txt );
}
}
六、使用计时器:
using System;
using System.Timers; class TestTimer
{
public static void Main()
{
Timer timer = new Timer();
timer.Elapsed += new ElapsedEventHandler( DisplayTimeEvent );
timer.Interval = 1000;
timer.Start();
timer.Enabled = true; while ( Console.Read() != 'q' )
{
//-------------
}
}
public static void DisplayTimeEvent( object source, ElapsedEventArgs e )
{
Console.Write(\r{0}, DateTime.Now);
}
}
七、调用外部程序:
class Test
{
static void Main(string[] args)
{
System.Diagnostics.Process.Start(notepad.exe);
}
} ADO.NET方面的:
八、连接Access数据库:
using System;
using System.Data;
using System.Data.OleDb; class TestADO
{
static void Main(string[] args)
{
string strDSN = Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\\test.mdb;
string strSQL = SELECT * FROM employees ; OleDbConnection conn = new OleDbConnection(strDSN);
OleDbCommand cmd = new OleDbCommand( strSQL, conn );
OleDbDataReader reader = null;
try
{
conn.Open();
reader = cmd.ExecuteReader();
while (reader.Read() )
{
Console.WriteLine(First Name:{0}, Last Name:{1}, reader[FirstName], reader[LastName]);
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
finally
{
conn.Close();
}
}
}
九、连接SQL Server数据库:
using System;
using System.Data.SqlClient; public class TestADO
{
public static void Main()
{
SqlConnection conn = new SqlConnection(Data Source=localhost; Integrated Security=SSPI; Initial Catalog=pubs);
SqlCommand cmd = new SqlCommand(SELECT * FROM employees, conn);
try
{
conn.Open(); SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(First Name: {0}, Last Name: {1}, reader.GetString(0), reader.GetString(1));
} reader.Close();
conn.Close();
}
catch(Exception e)
{
Console.WriteLine(Exception Occured -->> {0},e);
}
}
}
十、从SQL内读数据到XML:
using System;
using System.Data;
using System.Xml;
using System.Data.SqlClient;
using System.IO; public class TestWriteXML
{
public static void Main()
{ String strFileName=c:/temp/output.xml; SqlConnection conn = new SqlConnection(server=localhost;uid=sa;pwd=;database=db); String strSql = SELECT FirstName, LastName FROM employees; SqlDataAdapter adapter = new SqlDataAdapter(); adapter.SelectCommand = new SqlCommand(strSql,conn); // Build the DataSet
DataSet ds = new DataSet(); adapter.Fill(ds, employees); // Get a FileStream object
FileStream fs = new FileStream(strFileName,FileMode.OpenOrCreate,FileAccess.Write); // Apply the WriteXml method to write an XML document
ds.WriteXml(fs); fs.Close(); }
}
十一、用ADO添加数据到数据库中:
using System;
using System.Data;
using System.Data.OleDb; class TestADO
{
static void Main(string[] args)
{
string strDSN = Provider=Microsoft.Jet.OLEDB.4.0;DataSource=c:\test.mdb;
string strSQL = INSERT INTO Employee(FirstName, LastName) VALUES('FirstName', 'LastName') ; // create Objects of ADOConnection and ADOCommand
OleDbConnection conn = new OleDbConnection(strDSN);
OleDbCommand cmd = new OleDbCommand( strSQL, conn );
try
{
conn.Open();
cmd.ExecuteNonQuery();
}
catch (Exception e)
{
Console.WriteLine(Oooops. I did it again:\n{0}, e.Message);
}
finally
{
conn.Close();
}
}
}
十二、使用OLEConn连接数据库:
using System;
using System.Data;
using System.Data.OleDb; class TestADO
{
static void Main(string[] args)
{
string strDSN = Provider=Microsoft.Jet.OLEDB.4.0;DataSource=c:\test.mdb;
string strSQL = SELECT * FROM employee ; OleDbConnection conn = new OleDbConnection(strDSN);
OleDbDataAdapter cmd = new OleDbDataAdapter( strSQL, conn ); conn.Open();
DataSet ds = new DataSet();
cmd.Fill( ds, employee );
DataTable dt = ds.Tables[0]; foreach( DataRow dr in dt.Rows )
{
Console.WriteLine(First name: + dr[FirstName].ToString() + Last name: + dr[LastName].ToString());
}
conn.Close();
}
}
十三、读取表的属性:
using System;
using System.Data;
using System.Data.OleDb; class TestADO
{
static void Main(string[] args)
{
string strDSN = Provider=Microsoft.Jet.OLEDB.4.0;DataSource=c:\test.mdb;
string strSQL = SELECT * FROM employee ; OleDbConnection conn = new OleDbConnection(strDSN);
OleDbDataAdapter cmd = new OleDbDataAdapter( strSQL, conn ); conn.Open();
DataSet ds = new DataSet();
cmd.Fill( ds, employee );
DataTable dt = ds.Tables[0]; Console.WriteLine(Field Name DataType Unique AutoIncrement AllowNull);
Console.WriteLine(==================================================================);
foreach( DataColumn dc in dt.Columns )
{
Console.WriteLine(dc.ColumnName+ , +dc.DataType + ,+dc.Unique + ,+dc.AutoIncrement+ ,+dc.AllowDBNull );
}
conn.Close();
}
} ASP.NET方面的
十四、一个ASP.NET程序:
<%@ Page Language=C# %>
<script runat=server> void Button1_Click(Object sender, EventArgs e)
{
Label1.Text=TextBox1.Text;
} </script>
<html>
<head>
</head>
<body>
<form runat=server>
<p>
<br />
Enter your name: <asp:TextBox id=TextBox1 runat=server></asp:TextBox>
</p>
<p>
<b><asp:Label id=Label1 runat=server Width=247px></asp:Label></b>
</p>
<p>
<asp:Button id=Button1 onclick=Button1_Click runat=server Text=Submit></asp:Button>
</p>
</form>
</body>
</html> WinForm开发:
十五、一个简单的WinForm程序:
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data; public class SimpleForm : System.Windows.Forms.Form
{ private System.ComponentModel.Container components = null;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.TextBox textBox1;
public SimpleForm()
{
InitializeComponent();
} protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
} #region Windows Form Designer generated code
private void InitializeComponent()
{ this.components = new System.ComponentModel.Container();
this.Size = new System.Drawing.Size(300,300);
this.Text = Form1; this.button1 = new System.Windows.Forms.Button();
this.textBox1 = new System.Windows.Forms.TextBox();
this.SuspendLayout();
//
// button1
// this.button1.Location = new System.Drawing.Point(8, 16);
this.button1.Name = button1;
this.button1.Size = new System.Drawing.Size(80, 24);
this.button1.TabIndex = 0;
this.button1.Text = button1; //
// textBox1
//
this.textBox1.Location = new System.Drawing.Point(112, 16);
this.textBox1.Name = textBox1;
this.textBox1.Size = new System.Drawing.Size(160, 20);
this.textBox1.TabIndex = 1;
this.textBox1.Text = textBox1;
//
// Form1
// this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(292, 273);
this.Controls.AddRange(new System.Windows.Forms.Control[] {
this.textBox1,
this.button1});
this.Name = Form1;
this.Text = Form1;
this.ResumeLayout(false); }
#endregion [STAThread]
static void Main()
{
Application.Run(new SimpleForm());
}
}
十六、运行时显示自己定义的图标:
//load icon and set to form
System.Drawing.Icon ico = new System.Drawing.Icon(@c:\temp\app.ico);
this.Icon = ico;
十七、添加组件到ListBox中:
private void Form1_Load(object sender, System.EventArgs e)
{
string str = First item;
int i = 23;
float flt = 34.98f;
listBox1.Items.Add(str);
listBox1.Items.Add(i.ToString());
listBox1.Items.Add(flt.ToString());
listBox1.Items.Add(Last Item in the List Box);
} 网络方面的:
十八、取得IP地址:
using System;
using System.Net; class GetIP
{
public static void Main()
{
IPHostEntry ipEntry = Dns.GetHostByName (localhost);
IPAddress [] IpAddr = ipEntry.AddressList;
for (int i = 0; i < IpAddr.Length; i++)
{
Console.WriteLine (IP Address {0}: {1} , i, IpAddr.ToString ());
}
}
}
十九、取得机器名称:
using System;
using System.Net; class GetIP
{
public static void Main()
{
Console.WriteLine (Host name : {0}, Dns.GetHostName());
}
}
C# 常用代码片段的更多相关文章
- C#常用代码片段备忘
以下是从visual studio中整理出来的常用代码片段,以作备忘 快捷键: eh 用途: 类中事件实现函数模板 private void MyMethod(object sender, Event ...
- 36个Android开发常用代码片段
//36个Android开发常用代码片段 //拨打电话 public static void call(Context context, String phoneNumber) { context.s ...
- Jquery学习总结(1)——Jquery常用代码片段汇总
1. 禁止右键点击 ? 1 2 3 4 5 $(document).ready(function(){ $(document).bind("contextmenu",fun ...
- jQuery常用代码片段
检测IE浏览器 在进行CSS设计时,IE浏览器对开发者及设计师而言无疑是个麻烦.尽管IE6的黑暗时代已经过去,IE浏览器家族的人气亦在不断下滑,但我们仍然有必要对其进行检测.当然,以下片段亦可用于检测 ...
- Vue3.0常用代码片段和开发插件
Vue3 Snippets for Visual Studio Code Vue3 Snippets源码 Vue3 Snippets下载 This extension adds Vue3 Code S ...
- Ext.NET Ext.JS 常用代码片段摘录
引言 最近写代码突然有"一把梭"的感觉, 不管三七二十一先弄上再说. 换别人的说法, 这应该是属于"做项目"风格法吧. 至于知识体系, 可以参考官方或者更权威的 ...
- Play常用代码片段 http://www.anool.net/?p=625
持续更新中: (1)按照降序查询: List<Entity> entities= Entity.find("order by id desc").fetch(2); ...
- Android开发常用代码片段
拨打电话 public static void call(Context context, String phoneNumber) { context.startActivity( new Inten ...
- ide phpStorm常用代码片段设置
1.打开设置(File -> Settings) 2.如图 3 . 最后,在PHP文件中输入 ll 并按 TAB 即可打出代码块
- js 常用代码片段
一.预加载图像 如果你的网页中需要使用大量初始不可见的(例如,悬停的)图像,那么可以预加载这些图像. function preloadImages(){ for(var i=0;i<argume ...
随机推荐
- OpenCV: OpenCV人脸检测框可信度排序
参考文章:http://blog.csdn.net/hua_007/article/details/45368607 使用OpenCV进行人脸识别时,使用 casecade.detectMultiSc ...
- 据说现在很缺设计师,阿里云的LOGO是用键盘打出来的……
今天,阿里云发布了自己的新LOGO,官方的解读是:“[]”这个呢其实是代码中常用的一个符号,代表着计算:中间的“—”则代表流动的数据.在官网等平台上,阿里云新LOGO是动态的,中间的“—”会匀速移动, ...
- (转)基于MVC4+EasyUI的Web开发框架经验总结(12)--利用Jquery处理数据交互的几种方式
http://www.cnblogs.com/wuhuacong/p/4085682.html 在基于MVC4+EasyUI的Web开发框架里面,大量采用了Jquery的方法,对数据进行请求或者提交, ...
- 浅谈Web缓存-缓存的实现过程详解
在前端开发中,性能一直都是被大家所重视的一点,然而判断一个网站的性能最直观的就是看网页打开的速度.其中提高网页反应速度的一个方式就是使用缓存.一个优秀的缓存策略可以缩短网页请求资源的距离,减少延迟,并 ...
- 团体程序设计天梯赛-练习集-L1-033. 出生年
L1-033. 出生年 以上是新浪微博中一奇葩贴:“我出生于1988年,直到25岁才遇到4个数字都不相同的年份.”也就是说,直到2013年才达到“4个数字都不相同”的要求.本题请你根据要求,自动填充“ ...
- Java基础学习笔记三 正则表达式和校验、Date、DateFormat、Calendar
正则表达式 正则表达式(英语:Regular Expression,在代码中常简写为regex).正则表达式是一个字符串,使用单个字符串来描述.用来定义匹配规则,匹配一系列符合某个句法规则的字符串.在 ...
- boost asio异步读写网络聊天程序客户端 实例详解
boost官方文档中聊天程序实例讲解 数据包格式chat_message.hpp <pre name="code" class="cpp">< ...
- PAT_A1030#Travel Plan
Source: PAT A1030 Travel Plan (30 分) Description: A traveler's map gives the distances between citie ...
- loadrunner录制不了
我在使用loadrunner过程中遇到的问题是,录制脚本时候能够打开firefox,但是无法打开IE,降低IE版本以后仍然不行. 1.在录制脚本时Start Recoding中,默认如下,这样有可能I ...
- 【剑指Offer】 24、二叉树中和为某一值的路径
题目描述: 输入一颗二叉树的根结点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径.路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径.(注意: 在返回值的list中, ...