C# 常用代码整理
1
【字号:大 小】 2 ![]() 3 一、从控制台读取东西代码片断:4 using System;5 ![]() 6 class TestReadConsole7 {8 public static void Main()9 {10 Console.Write(Enter your name:);11 string strName = Console.ReadLine();12 Console.WriteLine( Hi + strName);13 }14 }15 二、读文件代码片断:16 using System; 17 using System.IO; 18 ![]() 19 public class TestReadFile 20 { 21 public static void Main(String[] args) 22 { 23 // Read text file C:\temp\test.txt 24 FileStream fs = new FileStream(@c:\temp\test.txt , FileMode.Open, FileAccess.Read); 25 StreamReader sr = new StreamReader(fs); 26 27 String line=sr.ReadLine();28 while (line!=null)29 {30 Console.WriteLine(line);31 line=sr.ReadLine();32 } 33 34 sr.Close();35 fs.Close();36 } 37 } 38 三、写文件代码:39 using System; 40 using System.IO; 41 ![]() 42 public class TestWriteFile 43 { 44 public static void Main(String[] args) 45 { 46 // Create a text file C:\temp\test.txt 47 FileStream fs = new FileStream(@c:\temp\test.txt , FileMode.OpenOrCreate, FileAccess.Write); 48 StreamWriter sw = new StreamWriter(fs); 49 // Write to the file using StreamWriter class 50 sw.BaseStream.Seek(0, SeekOrigin.End); 51 sw.WriteLine( First Line ); 52 sw.WriteLine( Second Line); 53 sw.Flush(); 54 } 55 } 56 四、拷贝文件:57 using System;58 using System.IO;59 ![]() 60 class TestCopyFile61 {62 public static void Main()63 {64 File.Copy(c:\\temp\\source.txt, C:\\temp\\dest.txt ); 65 }66 }67 五、移动文件:68 using System;69 using System.IO;70 ![]() 71 class TestMoveFile72 {73 public static void Main()74 {75 File.Move(c:\\temp\\abc.txt, C:\\temp\\def.txt ); 76 }77 }78 六、使用计时器:79 using System;80 using System.Timers;81 ![]() 82 class TestTimer83 {84 public static void Main()85 {86 Timer timer = new Timer();87 timer.Elapsed += new ElapsedEventHandler( DisplayTimeEvent );88 timer.Interval = 1000;89 timer.Start();90 timer.Enabled = true;91 ![]() 92 while ( Console.Read() != 'q' )93 {94 ![]() 95 }96 }97 ![]() 98 public static void DisplayTimeEvent( object source, ElapsedEventArgs e )99 {100 Console.Write(\r{0}, DateTime.Now);101 }102 }103 七、调用外部程序:104 class Test 105 { 106 static void Main(string[] args) 107 { 108 System.Diagnostics.Process.Start(notepad.exe); 109 } 110 }111 ![]() 112 ADO.NET方面的:113 八、连接Access数据库:114 using System;115 using System.Data;116 using System.Data.OleDb;117 ![]() 118 class TestADO119 {120 static void Main(string[] args)121 {122 string strDSN = Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\\test.mdb;123 string strSQL = SELECT * FROM employees ;124 ![]() 125 OleDbConnection conn = new OleDbConnection(strDSN);126 OleDbCommand cmd = new OleDbCommand( strSQL, conn );127 OleDbDataReader reader = null;128 try129 {130 conn.Open();131 reader = cmd.ExecuteReader();132 while (reader.Read() )133 {134 Console.WriteLine(First Name:{0}, Last Name:{1}, reader[FirstName], reader[LastName]);135 }136 }137 catch (Exception e)138 {139 Console.WriteLine(e.Message);140 }141 finally142 {143 conn.Close();144 }145 }146 } 147 九、连接SQL Server数据库:148 using System;149 using System.Data.SqlClient;150 ![]() 151 public class TestADO152 {153 public static void Main()154 {155 SqlConnection conn = new SqlConnection(Data Source=localhost; Integrated Security=SSPI; Initial Catalog=pubs);156 SqlCommand cmd = new SqlCommand(SELECT * FROM employees, conn);157 try158 { 159 conn.Open();160 ![]() 161 SqlDataReader reader = cmd.ExecuteReader(); 162 while (reader.Read())163 {164 Console.WriteLine(First Name: {0}, Last Name: {1}, reader.GetString(0), reader.GetString(1));165 }166 167 reader.Close();168 conn.Close();169 }170 catch(Exception e)171 {172 Console.WriteLine(Exception Occured -->> {0},e);173 } 174 }175 }176 十、从SQL内读数据到XML:177 using System;178 using System.Data;179 using System.Xml;180 using System.Data.SqlClient; 181 using System.IO; 182 ![]() 183 public class TestWriteXML184 { 185 public static void Main()186 { 187 ![]() 188 String strFileName=c:/temp/output.xml;189 ![]() 190 SqlConnection conn = new SqlConnection(server=localhost;uid=sa;pwd=;database=db);191 ![]() 192 String strSql = SELECT FirstName, LastName FROM employees; 193 ![]() 194 SqlDataAdapter adapter = new SqlDataAdapter(); 195 ![]() 196 adapter.SelectCommand = new SqlCommand(strSql,conn);197 ![]() 198 // Build the DataSet199 DataSet ds = new DataSet();200 ![]() 201 adapter.Fill(ds, employees);202 ![]() 203 // Get a FileStream object204 FileStream fs = new FileStream(strFileName,FileMode.OpenOrCreate,FileAccess.Write);205 ![]() 206 // Apply the WriteXml method to write an XML document207 ds.WriteXml(fs);208 ![]() 209 fs.Close();210 ![]() 211 }212 }213 十一、用ADO添加数据到数据库中:214 using System;215 using System.Data; 216 using System.Data.OleDb; 217 ![]() 218 class TestADO219 { 220 static void Main(string[] args) 221 { 222 string strDSN = Provider=Microsoft.Jet.OLEDB.4.0;DataSource=c:\test.mdb; 223 string strSQL = INSERT INTO Employee(FirstName, LastName) VALUES('FirstName', 'LastName') ; 224 225 // create Objects of ADOConnection and ADOCommand 226 OleDbConnection conn = new OleDbConnection(strDSN); 227 OleDbCommand cmd = new OleDbCommand( strSQL, conn ); 228 try 229 { 230 conn.Open(); 231 cmd.ExecuteNonQuery(); 232 } 233 catch (Exception e) 234 { 235 Console.WriteLine(Oooops. I did it again:\n{0}, e.Message); 236 } 237 finally 238 { 239 conn.Close(); 240 } 241 } 242 } 243 十二、使用OLEConn连接数据库:244 using System;245 using System.Data; 246 using System.Data.OleDb; 247 ![]() 248 class TestADO249 { 250 static void Main(string[] args) 251 { 252 string strDSN = Provider=Microsoft.Jet.OLEDB.4.0;DataSource=c:\test.mdb; 253 string strSQL = SELECT * FROM employee ; 254 ![]() 255 OleDbConnection conn = new OleDbConnection(strDSN);256 OleDbDataAdapter cmd = new OleDbDataAdapter( strSQL, conn ); 257 ![]() 258 conn.Open();259 DataSet ds = new DataSet();260 cmd.Fill( ds, employee );261 DataTable dt = ds.Tables[0];262 ![]() 263 foreach( DataRow dr in dt.Rows )264 {265 Console.WriteLine(First name: + dr[FirstName].ToString() + Last name: + dr[LastName].ToString());266 }267 conn.Close(); 268 } 269 } 270 十三、读取表的属性:271 using System;272 using System.Data; 273 using System.Data.OleDb; 274 ![]() 275 class TestADO276 { 277 static void Main(string[] args) 278 { 279 string strDSN = Provider=Microsoft.Jet.OLEDB.4.0;DataSource=c:\test.mdb; 280 string strSQL = SELECT * FROM employee ; 281 ![]() 282 OleDbConnection conn = new OleDbConnection(strDSN);283 OleDbDataAdapter cmd = new OleDbDataAdapter( strSQL, conn ); 284 ![]() 285 conn.Open();286 DataSet ds = new DataSet();287 cmd.Fill( ds, employee );288 DataTable dt = ds.Tables[0];289 ![]() 290 Console.WriteLine(Field Name DataType Unique AutoIncrement AllowNull);291 Console.WriteLine(==================================================================);292 foreach( DataColumn dc in dt.Columns )293 {294 Console.WriteLine(dc.ColumnName+ , +dc.DataType + ,+dc.Unique + ,+dc.AutoIncrement+ ,+dc.AllowDBNull );295 }296 conn.Close(); 297 } 298 } 299 ![]() 300 ASP.NET方面的301 十四、一个ASP.NET程序:302 <%@ Page Language=C# %>303 <script runat=server>304 305 void Button1_Click(Object sender, EventArgs e) 306 {307 Label1.Text=TextBox1.Text;308 }309 ![]() 310 </script>311 <html>312 <head>313 </head>314 <body>315 <form runat=server>316 <p>317 <br />318 Enter your name: <asp:TextBox id=TextBox1 runat=server></asp:TextBox>319 </p>320 <p>321 <b><asp:Label id=Label1 runat=server Width=247px></asp:Label></b>322 </p>323 <p>324 <asp:Button id=Button1 onclick=Button1_Click runat=server Text=Submit></asp:Button>325 </p>326 </form>327 </body>328 </html>329 ![]() 330 WinForm开发:331 十五、一个简单的WinForm程序:332 using System;333 using System.Drawing;334 using System.Collections;335 using System.ComponentModel;336 using System.Windows.Forms;337 using System.Data;338 ![]() 339 ![]() 340 public class SimpleForm : System.Windows.Forms.Form341 {342 ![]() 343 private System.ComponentModel.Container components = null;344 private System.Windows.Forms.Button button1;345 private System.Windows.Forms.TextBox textBox1;346 public SimpleForm()347 {348 InitializeComponent();349 }350 ![]() 351 protected override void Dispose( bool disposing )352 {353 if( disposing )354 {355 if (components != null)356 {357 components.Dispose();358 }359 }360 base.Dispose( disposing );361 }362 ![]() 363 Windows Form Designer generated code407 ![]() 408 [STAThread]409 static void Main()410 {411 Application.Run(new SimpleForm());412 } 413 }414 十六、运行时显示自己定义的图标:415 //load icon and set to form416 System.Drawing.Icon ico = new System.Drawing.Icon(@c:\temp\app.ico);417 this.Icon = ico;418 十七、添加组件到ListBox中:419 private void Form1_Load(object sender, System.EventArgs e)420 {421 string str = First item;422 int i = 23;423 float flt = 34.98f; 424 listBox1.Items.Add(str);425 listBox1.Items.Add(i.ToString());426 listBox1.Items.Add(flt.ToString());427 listBox1.Items.Add(Last Item in the List Box);428 } 429 ![]() 430 网络方面的:431 十八、取得IP地址:432 using System;433 using System.Net;434 ![]() 435 class GetIP436 {437 public static void Main()438 {439 IPHostEntry ipEntry = Dns.GetHostByName (localhost);440 IPAddress [] IpAddr = ipEntry.AddressList;441 for (int i = 0; i < IpAddr.Length; i++)442 { 443 Console.WriteLine (IP Address {0}: {1} , i, IpAddr.ToString ());444 }445 }446 }447 十九、取得机器名称:448 using System;449 using System.Net;450 ![]() 451 class GetIP452 {453 public static void Main()454 {455 Console.WriteLine (Host name : {0}, Dns.GetHostName());456 }457 }458 二十、发送邮件:459 using System;460 using System.Web;461 using System.Web.Mail;462 ![]() 463 public class TestSendMail464 {465 public static void Main()466 {467 try468 {469 // Construct a new mail message 470 MailMessage message = new MailMessage();471 message.From = from@domain.com;472 message.To = pengyun@cobainsoft.com;473 message.Cc = ;474 message.Bcc = ;475 message.Subject = Subject;476 message.Body = Content of message;477 478 //if you want attach file with this mail, add the line below479 message.Attachments.Add(new MailAttachment(c:\\attach.txt, MailEncoding.Base64));480 481 // Send the message482 SmtpMail.Send(message); 483 System.Console.WriteLine(Message has been sent);484 }485 ![]() 486 catch(Exception ex)487 {488 System.Console.WriteLine(ex.Message.ToString());489 }490 ![]() 491 }492 }493 二十一、根据IP地址得出机器名称:494 using System;495 using System.Net;496 ![]() 497 class ResolveIP498 {499 public static void Main()500 {501 IPHostEntry ipEntry = Dns.Resolve(172.29.9.9);502 Console.WriteLine (Host name : {0}, ipEntry.HostName); 503 }504 }505 ![]() 506 GDI+方面的:507 二十二、GDI+入门介绍:508 using System;509 using System.Drawing;510 using System.Collections;511 using System.ComponentModel;512 using System.Windows.Forms;513 using System.Data;514 ![]() 515 public class Form1 : System.Windows.Forms.Form516 {517 private System.ComponentModel.Container components = null;518 ![]() 519 public Form1()520 {521 InitializeComponent();522 }523 ![]() 524 protected override void Dispose( bool disposing )525 {526 if( disposing )527 {528 if (components != null) 529 {530 components.Dispose();531 }532 }533 base.Dispose( disposing );534 }535 ![]() 536 Windows Form Designer generated code546 ![]() 547 [STAThread]548 static void Main() 549 {550 Application.Run(new Form1());551 }552 ![]() 553 private void Form1_Paint(object sender, System.Windows.Forms.PaintEventArgs e)554 {555 Graphics g=e.Graphics;556 g.DrawLine(new Pen(Color.Blue),10,10,210,110);557 g.DrawRectangle(new Pen(Color.Red),10,10,200,100);558 g.DrawEllipse(new Pen(Color.Yellow),10,150,200,100);559 }560 }561 ![]() 562 XML方面的:563 二十三、读取XML文件:564 using System;565 using System.Xml; 566 ![]() 567 class TestReadXML568 {569 public static void Main()570 {571 572 XmlTextReader reader = new XmlTextReader(C:\\test.xml);573 reader.Read();574 575 while (reader.Read())576 { 577 reader.MoveToElement();578 Console.WriteLine(XmlTextReader Properties Test);579 Console.WriteLine(===================); 580 ![]() 581 // Read this properties of element and display them on console582 Console.WriteLine(Name: + reader.Name);583 Console.WriteLine(Base URI: + reader.BaseURI);584 Console.WriteLine(Local Name: + reader.LocalName);585 Console.WriteLine(Attribute Count: + reader.AttributeCount.ToString());586 Console.WriteLine(Depth: + reader.Depth.ToString());587 Console.WriteLine(Line Number: + reader.LineNumber.ToString());588 Console.WriteLine(Node Type: + reader.NodeType.ToString());589 Console.WriteLine(Attribute Count: + reader.Value.ToString());590 } 591 } 592 } 593 二十四、写XML文件:594 using System; 595 using System.Xml; 596 ![]() 597 public class TestWriteXMLFile 598 { 599 public static int Main(string[] args) 600 { 601 try 602 { 603 // Creates an XML file is not exist 604 XmlTextWriter writer = new XmlTextWriter(C:\\temp\\xmltest.xml, null); 605 // Starts a new document 606 writer.WriteStartDocument(); 607 //Write comments 608 writer.WriteComment(Commentss: XmlWriter Test Program); 609 writer.WriteProcessingInstruction(Instruction,Person Record); 610 // Add elements to the file 611 writer.WriteStartElement(p, person, urn:person); 612 writer.WriteStartElement(LastName,); 613 writer.WriteString(Chand); 614 writer.WriteEndElement(); 615 writer.WriteStartElement(FirstName,); 616 writer.WriteString(Mahesh); 617 writer.WriteEndElement(); 618 writer.WriteElementInt16(age,, 25); 619 // Ends the document 620 writer.WriteEndDocument(); 621 } 622 catch (Exception e) 623 { 624 Console.WriteLine (Exception: {0}, e.ToString()); 625 } 626 return 0; 627 } 628 } 629 ![]() 630 Web Service方面的:631 二十五、一个Web Service的小例子:632 <% @WebService Language=C# Class=TestWS %>633 ![]() 634 using System.Web.Services;635 ![]() 636 public class TestWS : System.Web.Services.WebService637 {638 [WebMethod()]639 public string StringFromWebService()640 {641 return This is a string from web service.;642 }643 } |





}
}
浙公网安备 33010602011771号