基礎輸入輸出
控制台讀寫
Console.Write("Enter name: ");
string name = Console.ReadLine();
Console.WriteLine($"Hi {name}");
文件讀取
using (FileStream fs = new FileStream(@"c:\temp\test.txt", FileMode.Open, FileAccess.Read))
using (StreamReader sr = new StreamReader(fs))
{
string line;
while ((line = sr.ReadLine()) != null)
Console.WriteLine(line);
}
文件寫入
using (FileStream fs = new FileStream(@"c:\temp\test.txt", FileMode.OpenOrCreate, FileAccess.Write))
using (StreamWriter sw = new StreamWriter(fs))
{
sw.BaseStream.Seek(0, SeekOrigin.End);
sw.WriteLine("First Line");
sw.WriteLine("Second Line");
}
文件複製/移動
File.Copy(@"c:\temp\source.txt", @"c:\temp\dest.txt");
File.Move(@"c:\temp\abc.txt", @"c:\temp\def.txt");
計時器與外部進程
// Timer
var timer = new System.Timers.Timer(1000);
timer.Elapsed += (s, e) => Console.Write($"\r{DateTime.Now}");
timer.Start();
// 啟動外部程序
Process.Start("notepad.exe");
ADO.NET 數據訪問
Access (OleDb)
string connStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\\test.mdb";
using (var conn = new OleDbConnection(connStr))
using (var cmd = new OleDbCommand("SELECT * FROM employees", conn))
{
conn.Open();
using (var reader = cmd.ExecuteReader())
while (reader.Read())
Console.WriteLine($"{reader["FirstName"]} {reader["LastName"]}");
}
SQL Server (SqlClient)
using (var conn = new SqlConnection("Data Source=localhost;Integrated Security=SSPI;Initial Catalog=pubs"))
using (var cmd = new SqlCommand("SELECT * FROM employees", conn))
{
conn.Open();
using (var reader = cmd.ExecuteReader())
while (reader.Read())
Console.WriteLine($"{reader.GetString(0)} {reader.GetString(1)}");
}
DataSet 填充與寫 XML
var adapter = new SqlDataAdapter("SELECT * FROM employees", conn);
var ds = new DataSet();
adapter.Fill(ds, "employees");
ds.WriteXml(@"c:\temp\output.xml");
ASP.NET 頁面示例
<%@ Page Language="C#" %>
WinForms 基礎模板
public class SimpleForm : Form
{
private Button button1;
private TextBox textBox1;
public SimpleForm() { InitializeComponent(); }
private void InitializeComponent()
{
this.button1 = new Button { Location = new Point(8,16), Text = "Click" };
this.textBox1 = new TextBox { Location = new Point(112,16), Text = "Hello" };
this.Controls.AddRange(new Control[] { this.textBox1, this.button1 });
this.Text = "Demo";
}
[STAThread]
static void Main() { Application.Run(new SimpleForm()); }
}
網絡編程
獲取本機 IP
IPHostEntry entry = Dns.GetHostEntry("localhost");
foreach (IPAddress ip in entry.AddressList)
Console.WriteLine(ip);
Socket HTTP GET
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Connect(new IPEndPoint(Dns.GetHostAddresses("example.com")[0], 80));
socket.Send(Encoding.ASCII.GetBytes("GET / HTTP/1.1\r\nHost: example.com\r\nConnection: Close\r\n\r\n"));
// 接收循環...
發送郵件
var msg = new MailMessage
{
From = "from@domain.com",
To = "to@domain.com",
Subject = "Test",
Body = "Content"
};
SmtpMail.Send(msg);
GDI+ 繪圖
private void Form1_Paint(object sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
g.DrawLine(new Pen(Color.Blue), 10, 10, 210, 110);
g.DrawRectangle(new Pen(Color.Red), 10, 10, 200, 100);
g.DrawEllipse(new Pen(Color.Yellow), 10, 150, 200, 100);
}
XML 讀寫
XmlTextReader 讀取
using (var reader = new XmlTextReader("test.xml"))
{
while (reader.Read())
{
reader.MoveToElement();
Console.WriteLine($"Name:{reader.Name}, Value:{reader.Value}");
}
}
XmlTextWriter 寫入
using (var writer = new XmlTextWriter("output.xml", null))
{
writer.WriteStartDocument();
writer.WriteStartElement("person");
writer.WriteElementString("FirstName", "John");
writer.WriteElementString("LastName", "Doe");
writer.WriteEndElement();
writer.WriteEndDocument();
}
Web Service (ASMX)
<%@ WebService Language="C#" Class="TestWS" %>
using System.Web.Services;
public class TestWS : WebService
{
[WebMethod]
public string Hello() => "Hello from Web Service!";
}