C#常用代码总结

来源:互联网 发布:淘宝属于媒介消费吗 编辑:程序博客网 时间:2024/05/18 02:49

 1
  2
  3一、从控制台读取东西代码片断:
  4using System;
  5
  6class TestReadConsole
  7{
  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二、读文件代码片断:
 16using System;
 17using System.IO;
 18
 19public 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三、写文件代码:
 39using System;
 40using System.IO;
 41
 42public 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四、拷贝文件:
 57using System;
 58using System.IO;
 59
 60class TestCopyFile
 61{
 62    public static void Main()
 63    {
 64        File.Copy(c://temp//source.txt, C://temp//dest.txt ); 
 65    }
 66}
 67五、移动文件:
 68using System;
 69using System.IO;
 70
 71class TestMoveFile
 72{
 73    public static void Main()
 74    {
 75        File.Move(c://temp//abc.txt, C://temp//def.txt ); 
 76    }
 77}
 78六、使用计时器:
 79using System;
 80using System.Timers;
 81
 82class TestTimer
 83{
 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七、调用外部程序:
104class Test
105{
106    static void Main(string[] args)
107    {
108        System.Diagnostics.Process.Start(notepad.exe);
109    }
110}
111
112ADO.NET方面的:
113八、连接Access数据库:
114using System;
115using System.Data;
116using System.Data.OleDb;
117
118class TestADO
119{
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        try
129        {
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        finally
142        {
143            conn.Close();
144        }
145    }
146}
147九、连接SQL Server数据库:
148using System;
149using System.Data.SqlClient;
150
151public class TestADO
152{
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        try
158        {       
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:
177using System;
178using System.Data;
179using System.Xml;
180using System.Data.SqlClient;
181using System.IO;
182
183public class TestWriteXML
184{
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 DataSet
199        DataSet ds = new DataSet();
200
201        adapter.Fill(ds, employees);
202
203        // Get a FileStream object
204        FileStream fs = new FileStream(strFileName,FileMode.OpenOrCreate,FileAccess.Write);
205
206        // Apply the WriteXml method to write an XML document
207        ds.WriteXml(fs);
208
209        fs.Close();
210
211    }
212}
213十一、用ADO添加数据到数据库中:
214using System;
215using System.Data;  
216using System.Data.OleDb;  
217
218class TestADO
219{ 
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连接数据库:
244using System;
245using System.Data;  
246using System.Data.OleDb;  
247
248class TestADO
249{ 
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十三、读取表的属性:
271using System;
272using System.Data;  
273using System.Data.OleDb;  
274
275class TestADO
276{ 
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
300ASP.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
330WinForm开发:
331十五、一个简单的WinForm程序:
332using System;
333using System.Drawing;
334using System.Collections;
335using System.ComponentModel;
336using System.Windows.Forms;
337using System.Data;
338
339
340public class SimpleForm : System.Windows.Forms.Form
341{
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 code#region Windows Form Designer generated code
364    private void InitializeComponent()
365    {
366
367        this.components = new System.ComponentModel.Container();
368        this.Size = new System.Drawing.Size(300,300);
369        this.Text = Form1;
370
371        this.button1 = new System.Windows.Forms.Button();
372        this.textBox1 = new System.Windows.Forms.TextBox();
373        this.SuspendLayout();
374    //
375    // button1
376    //
377
378    this.button1.Location = new System.Drawing.Point(8, 16);
379    this.button1.Name = button1;
380    this.button1.Size = new System.Drawing.Size(80, 24);
381    this.button1.TabIndex = 0;
382    this.button1.Text = button1;
383
384    //
385    // textBox1
386    //
387    this.textBox1.Location = new System.Drawing.Point(112, 16);
388    this.textBox1.Name = textBox1;
389    this.textBox1.Size = new System.Drawing.Size(160, 20);
390    this.textBox1.TabIndex = 1;
391    this.textBox1.Text = textBox1;
392    //
393    // Form1
394    //
395
396    this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
397    this.ClientSize = new System.Drawing.Size(292, 273);
398    this.Controls.AddRange(new System.Windows.Forms.Control[] {
399    this.textBox1,
400    this.button1});
401    this.Name = Form1;
402    this.Text = Form1;
403    this.ResumeLayout(false);
404
405    }
406    #endregion
407
408    [STAThread]
409    static void Main()
410    {
411        Application.Run(new SimpleForm());
412    }
413}
414十六、运行时显示自己定义的图标:
415//load icon and set to form
416System.Drawing.Icon ico = new System.Drawing.Icon(@c:/temp/app.ico);
417this.Icon = ico;
418十七、添加组件到ListBox中:
419private 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地址:
432using System;
433using System.Net;
434
435class GetIP
436{
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十九、取得机器名称:
448using System;
449using System.Net;
450
451class GetIP
452{
453    public static void Main()
454    {
455          Console.WriteLine (Host name : {0}, Dns.GetHostName());
456    }
457}
458二十、发送邮件:
459using System;
460using System.Web;
461using System.Web.Mail;
462
463public class TestSendMail
464{
465    public static void Main()
466    {
467        try
468        {
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 below
479            message.Attachments.Add(new MailAttachment(c://attach.txt, MailEncoding.Base64));
480 
481            // Send the message
482            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地址得出机器名称:
494using System;
495using System.Net;
496
497class ResolveIP
498{
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
506GDI+方面的:
507二十二、GDI+入门介绍:
508using System;
509using System.Drawing;
510using System.Collections;
511using System.ComponentModel;
512using System.Windows.Forms;
513using System.Data;
514
515public class Form1 : System.Windows.Forms.Form
516{
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 code#region Windows Form Designer generated code
537    private void InitializeComponent()
538    {
539        this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
540        this.ClientSize = new System.Drawing.Size(292, 273);
541        this.Name = Form1;
542        this.Text = Form1;
543        this.Paint += new System.Windows.Forms.PaintEventHandler(this.Form1_Paint);
544    }
545    #endregion
546
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
562XML方面的:
563二十三、读取XML文件:
564using System;
565using System.Xml; 
566
567class TestReadXML
568{
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 console
582            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文件:
594using System;
595using System.Xml;
596
597public 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
630Web Service方面的:
631二十五、一个Web Service的小例子:
632<% @WebService Language=C# Class=TestWS %>
633
634using System.Web.Services;
635
636public class TestWS : System.Web.Services.WebService
637{
638    [WebMethod()]
639    public string StringFromWebService()
640    {
641        return This is a string from web service.;
642    }
643}
644

原创粉丝点击