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;
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;
// 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 );
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 );
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 {
[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()); } } 二十、發送郵件: 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 = [email protected]; message.To = [email protected]; 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); }
} } 二十一、根據IP地址得出機器名稱: using System; using System.Net;
class ResolveIP { public static void Main() { IPHostEntry ipEntry = Dns.Resolve(172.29.9.9); Console.WriteLine (Host name : {0}, ipEntry.HostName); } }
GDI+方面的: 二十二、GDI+入門介紹: using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data;
public class Form1 : System.Windows.Forms.Form { private System.ComponentModel.Container components = null;
XML方面的: 二十三、讀取XML文件: using System; using System.XML;
class TestReadXML { public static void Main() {
XmlTextReader reader = new XmlTextReader(C:\\test.XML); reader.Read();
while (reader.Read()) { reader.MoveToElement(); Console.WriteLine(XMLTextReader PropertIEs Test); Console.WriteLine(===================);
// Read this propertIEs of element and display them on console Console.WriteLine(Name: + reader.Name); Console.WriteLine(Base URI: + reader.BaseURI); Console.WriteLine(Local Name: + reader.LocalName); Console.WriteLine(Attribute Count: + reader.AttributeCount.ToString()); Console.WriteLine(Depth: + reader.Depth.ToString()); Console.WriteLine(Line Number: + reader.LineNumber.ToString()); Console.WriteLine(Node Type: + reader.NodeType.ToString()); Console.WriteLine(Attribute Count: + reader.Value.ToString()); } } } 二十四、寫XML文件: using System; using System.XML;
public class TestWriteXMLFile { public static int Main(string[] args) { try { // Creates an XML file is not exist XmlTextWriter writer = new XmlTextWriter(C:\\temp\\xmltest.XML, null); // Starts a new document writer.WriteStartDocument(); //Write comments writer.WriteComment(Commentss: XMLWriter Test Program); writer.WriteProcessingInstruction(Instruction,Person Record); // Add elements to the file writer.WriteStartElement(p, person, urn:person); writer.WriteStartElement(LastName,); writer.WriteString(Chand); writer.WriteEndElement(); writer.WriteStartElement(FirstName,); writer.WriteString(Mahesh); writer.WriteEndElement(); writer.WriteElementInt16(age,, 25); // Ends the document writer.WriteEndDocument(); } catch (Exception e) { Console.WriteLine (Exception: {0}, e.ToString()); } return 0; } }
Web Service方面的: 二十五、一個Web Service的小例子: <% @WebService Language=C# Class=TestWS %>
using System.Web.Services;
public class TestWS : System.Web.Services.WebService { [WebMethod()] public string StringFromWebService() { return This is a string from web service.; } }