C#入门代码集

Wesley13
• 阅读 562

在QQ群聊天中,曾经有人问一些基础性问题。现在这里提供C#基本入门的代码集合20个,涵盖下面
基础语法;ADO.NET方面的;网络方面的:XML方面的:Web Service方面的.C#入门代码集

一、从控制台读取东西代码片断:

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();    }}

网络方面的:
十四、取得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 = "from@domain.com";            message.To = "pengyun@cobainsoft.com";            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");        }        catch (Exception ex)        {            System.Console.WriteLine(ex.Message.ToString());        }    }}

十七:根据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);    }}

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", "urnerson");            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的小例子:

using System.Web.Services;public class TestWS : System.Web.Services.WebService{    [WebMethod()]    public string StringFromWebService()    {        return "This is a string from web service.";    }}
点赞
收藏
评论区
推荐文章
blmius blmius
3年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Jacquelyn38 Jacquelyn38
3年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
Wesley13 Wesley13
3年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Stella981 Stella981
3年前
HIVE 时间操作函数
日期函数UNIX时间戳转日期函数: from\_unixtime语法:   from\_unixtime(bigint unixtime\, string format\)返回值: string说明: 转化UNIX时间戳(从19700101 00:00:00 UTC到指定时间的秒数)到当前时区的时间格式举例:hive   selec
Wesley13 Wesley13
3年前
Unity横屏
Android下发现Unity里面的Player设置,并不能完全有效,比如打开了自动旋转,启动的时候还是会横屏,修改XML添加以下代码<applicationandroid:icon"@drawable/ic\_launcher"                    android:label"@string/app\_name"
Stella981 Stella981
3年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Stella981 Stella981
3年前
Gson之实例五
前面四篇博客基本上可以满足我们处理的绝大多数需求,但有时项目中对json有特殊的格式规定.比如下面的json串解析:{"tableName":"students","tableData":{"id":1,"name":"李坤","birthDay":"Jun 22, 2012 9:54:49 PM"},{"id":2,"name":"曹贵生"
Wesley13 Wesley13
3年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
10个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这