Some simple examples of C #

xiaoxiao2021-03-06  41

General small things: 1. Reading something from the console: USING SYSTEM; Class TestreadConsole {public static void main () {Console.write ("Enter your name:"); string strname = console.readline (); Console.writeline ("Hi" strName);}} 2, read file code pieces: use 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 ();}} 3, write file code: use system; use 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 (); #Region Write the client file to the temporary directory of the server httppostedfile hpf = fileimport.postedfile; string fullfilename = HPF.FileName;

string FileName = System.IO.Path.GetFileNameWithoutExtension (fullFileName); string ExtendName = System.IO.Path.GetExtension (fullFileName);.. string FilePath = this.ViewState [ "FilePath"] ToString () Trim () @ " Temp / " filename system.datetime.now.tostring (" u "). Replace (": "," - ") extendName; System.IO.FileStream Write

try {System.IO.Stream imgdatastream = fileImport.PostedFile.InputStream; int imgdatalen = fileImport.PostedFile.ContentLength; byte [] imgdata = new byte [imgdatalen]; int n = imgdatastream.Read (imgdata, 0, imgdatalen);

IF (system.io.file.exists (filepath)) {system.io.file.delete (filepath);} // filestream fs = new filestream (filepath, filemode.openorcreate, fileaccess.write); // // fs .Write (IMGDATA, 0, IMGDATALEN); // fs.close ();

Write = system.io.file.create (filepath); Write.Write (IMGDATA, 0, IMGDATA.CLOSE (); IMGDataStream.close (); if (System.IO.File.exists (FilePath) ) {System.io.file.delete (FilePath);}} catch (exception ex) {throw ex;} #endregion}} four, copy file: use system; using system.io;

Class testcopyfile {public static void main () {file.copy ("c: //temp//source.txt");}} 5, mobile files: USING SYSTEM Using system.io;

Class testmovefile {public static void main () {file.move ("c: //temp//Abc.txt");}} 6, usage timer: 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);}} seven, call external programs: class test {static void main (string [] args) { System.diagnostics.Process.Start ("NOTEPAD.EXE");}} ADO.NET: Eight, Connect Access Database: Using System; Using System.Data; Using System.Data.OLDB;

Class testo {static void main (string "args) {string strdsn =" provcer = microsoft.jet.OLDB.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 ();}}} Nine, connect SQL Server database: use system; use 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 (); sqldatarader 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) }}} 10, read data from SQL to XML: use system.data; use system.xml; use 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 ();

}} 11, add data to the database with ADO: use system; use system.data; use 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 (); (Exception E) {Console.Writeline ("OOOOPS. I DID IT AGAIN: / N {0}", E.MESSAGE);} finally {conn.close ();}}} OLECONN connection database: using system; using system.data; using system.data.oledb; class testo {static void main (string "args) {string strdsn =" provcer = 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];

"DATAROW DR IN DT.ROWS) {Console.Writeline (" first name: " DR [" firstname "]. TOSTRING () " Last Name: " DR [" Lastname "]. TOSTRING ());} Conn.close ();}} 13. The properties of the read table: use system; use system.data; use 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. Dattype "," DC.AutoInCrement "," DC.AllowdBnull);} () (); ();}} ASP.NET Fourteen, an ASP.NET program: <% @ page language = "c #"%>