首页 > 其他 > 详细

C# 常用代码片段

时间:2014-03-12 15:42:36      阅读:326      评论:0      收藏:0      [点我收藏+]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
一、从控制台读取东西代码片断:
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# 常用代码片段,布布扣,bubuko.com

C# 常用代码片段

原文:http://www.cnblogs.com/nanphon/p/3595992.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!