C#入门代码

最近很忙,忙着学习,忙着出报纸,忙着写总结,忙着计划,忙着考试……
    没有写一些学习.NET的心得了,过一些天吧,今天看到一篇文章很不错,特地转载了一下

 

数据挖掘交友

一、从控制台读取东西代码片断:
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: emp est.txt
        FileStream fs = new FileStream(@c: emp est.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: emp est.txt
        FileStream fs = new FileStream(@c: emp est.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( {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: est.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: {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: est.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: est.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: empapp.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 = 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);        
     }
} 数据挖掘工具

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;

    public Form1()
    {
        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.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
        this.ClientSize = new System.Drawing.Size(292, 273);
        this.Name = Form1;
        this.Text = Form1;
        this.Paint += new System.Windows.Forms.PaintEventHandler(this.Form1_Paint);
    }
    #endregion 数据挖掘工具

    [STAThread]
    static void Main()
    {
        Application.Run(new Form1());
    }

数据挖掘论坛

    private void Form1_Paint(object sender, System.Windows.Forms.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方面的:
二十三、读取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.;
    }
} 数据挖掘实验室

http://www.cnblogs.com/lyj/archive/2007/01/09/616053.html

数据挖掘工具

[数据挖掘专家] [数据挖掘研究院] [数据挖掘论坛] [数据挖掘实验室]
上一篇:利用C#实现分布式数据库查询
下一篇:C#入门代码
最新评论共有 0 位网友发表了评论 , 查看所有评论
发表评论( 不能超过250字,需审核,请自觉遵守互联网相关政策法规。 )
匿名?
数据挖掘网站导航 数据挖掘论坛导航
  • 数据挖掘工具
  • 数据挖掘论坛
  • DataCruncher - Cognos
  • MineSet - MathSoft
  • Intelligent Miner - GainSmarts
  • Sqlserver - SAS - Clementine
  • CART - Weka - WizSoft
  • NeuroShell - ModelQuest
  • data mining tools - Darwin
  • 数据挖掘交友
  • 数据挖掘博客
  • 数据挖掘工具
  • 数据挖掘资源
  • 数据挖掘技术算法
  • 数据挖掘相关期刊、会议
  • 研究院联盟合作专区
  • 数据挖掘基础与相关技术
  • 数据挖掘厂商与就业
  • 数据挖掘研究者乐园
  • 知名厂商数据挖掘工具资料
  • 国内数据挖掘实验室
  • Foreign Data Mining Lab
  • 热点关注
  • 挑战C#学习的最快速度
  • C#模仿QQ截图功能
  • C# 关于开机自动运行程序方式之一
  • 第一章 C#简介
  • 利用C#实现分布式数据库查询
  • Visual Studio 2005 Hands-On Tutorial - P
  • C#入门代码
  • .NET架构与模式探索
  • 用C#代码编写的SN快速输入工具
  • C# 关于开机自动运行程序方式之一
  • 论坛最新话题
  • Foundations of Statistical Natural Langu
  • Game Theory meet Data Mining: A Recent P
  • System Building: How does it help or hin
  • 数据挖掘与Clementine培训
  • 新手报到
  • 求 SASEM 客户流失预测分析
  • 数据挖掘工程师/搜索研究院—北京——无线
  • 数据挖掘入门介绍(如何着手数据挖掘)
  • Information Overload Survey Results
  • The INEX 2005 Workshop on Element Retrie
  • 相关资讯
  • 彻底剖析C# 2.0泛型类的创建和使用
  • 对C# 2.0中匿名方法的怀疑分析
  • EasySP管理解决方案基于Microsoft .NET架构
  • .NET架构与模式探索
  • .NET架构的核心开发技术
  • 用C#代码编写的SN快速输入工具
  • C#链接数据库技巧
  • C#设计模式编程之抽象工厂模式新解
  • 第一章 C#简介
  • 第七章 异常处理
  • 数据挖掘实验室资料
  • 数据挖掘博客地址
  • 数据挖掘实验室网站地址
  • Prepare for Medicare audits by using dat
  • 注册成为SAS用户与爱好者俱乐部会员
  • 水南梅
  • 明日烟
  • 新人报道
  • 下载
  • 厦门服务器托管,450元/月—0592-5177319 高
  • 买空间送域名--0592-5177319 高静