顯示具有 C# 標籤的文章。 顯示所有文章
顯示具有 C# 標籤的文章。 顯示所有文章

2013年8月21日 星期三

寫入XML檔案

寫入XML檔案

using System;
using System.IO;
using System.Xml;

public class Sample
{
  private const string filename = "sampledata.xml";

  public static void Main()
  {

     XmlTextWriter writer = new XmlTextWriter (filename, null);
     //Use indenting for readability.
     writer.Formatting = Formatting.Indented;

     writer.WriteComment("sample XML fragment");

     //Write an element (this one is the root).
     writer.WriteStartElement("bookstore");

     //Write the namespace declaration.
     writer.WriteAttributeString("xmlns", "bk", null, "urn:samples");

     writer.WriteStartElement("book");

     //Lookup the prefix and then write the ISBN attribute.
     string prefix = writer.LookupPrefix("urn:samples");
     writer.WriteStartAttribute(prefix, "ISBN", "urn:samples");
     writer.WriteString("1-861003-78");
     writer.WriteEndAttribute();     

     //Write the title.
     writer.WriteStartElement("title");
     writer.WriteString("The Handmaid's Tale");
     writer.WriteEndElement();

     //Write the price.
     writer.WriteElementString("price", "19.95");

     //Write the style element.
     writer.WriteStartElement(prefix, "style", "urn:samples");
     writer.WriteString("hardcover");
     writer.WriteEndElement();

     //Write the end tag for the book element.
     writer.WriteEndElement();

     //Write the close tag for the root element.
     writer.WriteEndElement();

     //Write the XML to file and close the writer.
     writer.Flush();
     writer.Close();

     //Read the file back in and parse to ensure well formed XML.
     XmlDocument doc = new XmlDocument();
     //Preserve white space for readability.
     doc.PreserveWhitespace = true;
     //Load the file
     doc.Load(filename);

     //Write the XML content to the console.
     Console.Write(doc.InnerXml);  

  }

}

另一種寫入XML檔案的方法

程式會在C槽下,產生檔案myXmlFile.xml
using System;
using System.Xml;

namespace ReadingXML2
{
    class Class1
    {
        static void Main(string[] args)
        {
            // Create a new file in C: dir
            XmlTextWriter textWriter = new XmlTextWriter("C:myXmFile.xml", null);
            textWriter.Formatting = Formatting.Indented;
            textWriter.Indentation = 4;
            // Opens the document
            textWriter.WriteStartDocument();
            // Write comments
            textWriter.WriteComment("First Comment XmlTextWriter Sample Example");
            textWriter.WriteComment("myXmlFile.xml in root dir");
            // Write first element
            textWriter.WriteStartElement("Student");
            textWriter.WriteStartElement("r", "RECORD", "urn:record");
            // Write next element
            textWriter.WriteStartElement("Name", "");
            textWriter.WriteString("Student");
            textWriter.WriteEndElement();
            // Write one more element
            textWriter.WriteStartElement("Address", ""); textWriter.WriteString("Colony");
            textWriter.WriteEndElement();
            // WriteChars
            char[] ch = new char[3];
            ch[0] = 'a';
            ch[1] = 'r';
            ch[2] = 'c';
            textWriter.WriteStartElement("Char");
            textWriter.WriteChars(ch, 0, ch.Length);
            textWriter.WriteEndElement();
            // Ends the document.
            textWriter.WriteEndDocument();
            // close writer
            textWriter.Close();
        }
    }
}

使用sqlite


//插入user資料表,一筆email和名字的紀錄。
_dbCmd.CommandText = "INSERT INTO user(email,name) VALUES ('email','name')";
_dbCmd.ExecuteNonQuery();

dbCmd.CommandText = "INSERT INTO user(email,name) VALUES ('dd@com','許秝維')";
_dbCmd.ExecuteNonQuery();

//更新user資料表,將名為bbn的名字都改為Codelicious
_dbCmd.CommandText = "UPDATE user SET name = 'Codelicious' WHERE name = 'bbn'";
_dbCmd.ExecuteNonQuery();  

//刪除user資料表
cmd.CommandText = "Drop Table user";
cmd.ExecuteNonQuery();

//在user資料表中,搜尋名為'許秝維',且email為dd@com的紀錄
_dbCmd.CommandText = "SELECT ID, name,email FROM user where name='許秝維' and email='dd@com'";
SQLiteDataReader reader = _dbCmd.ExecuteReader();
if (reader.HasRows)
{
 while (reader.Read())
 {
     Console.WriteLine("ID: " + reader.GetInt32(0));
     Console.WriteLine("name: " + reader.GetString(1));
     Console.WriteLine("email: " + reader.GetString(2));
 }
}
reader.Close();

//取得最後一筆紀錄
_dbCmd.CommandText = "SELECT  * FROM " + TABLE_FILE + " ORDER BY id DESC";
SQLiteDataReader reader = _dbCmd.ExecuteReader();
if (reader.HasRows)
{
 while (reader.Read())
 {
     Console.WriteLine("ID: " + reader.GetInt32(0));
     Console.WriteLine("name: " + reader.GetString(1));
     Console.WriteLine("email: " + reader.GetString(2));
     break;
 }
}
reader.Close();

//建立資料表
//Check table file exist?
_dbCmd.CommandText = "SELECT name FROM sqlite_master WHERE type='table' AND name='" + TABLE_FILE + "'";
dataReader = _dbCmd.ExecuteReader();
if (!dataReader.HasRows)
{
 dataReader.Close();
 _dbCmd.CommandText = "Create Table " + TABLE_FILE + " (id INTEGER PRIMARY KEY ASC, name ,path,tags,comment)";
 _dbCmd.ExecuteNonQuery();
}
else
{
 dataReader.Close();
}

//判斷屬性的資料型態
if (reader.HasRows)
{
    while (reader.Read())
    {
 for(int i=0;i<reader.FieldCount;i++)
 {
     if (reader.GetName(i).CompareTo("id") == 0)
     {
  if (reader.GetFieldType(i) == typeof(string))
  {
      dataResult[i]= reader.GetString(i);
  }
  else if (reader.GetFieldType(i) == typeof(Int64))
  {
      dataResult[i] = reader.GetInt64(i).ToString();
  }
  else if (reader.GetFieldType(i) == typeof(Int32))
  {
      dataResult[i] = reader.GetInt32(i).ToString();
  }
  else if (reader.GetFieldType(i) == typeof(Int16))
  {
      dataResult[i] = reader.GetInt16(i).ToString();
  }
  else if (reader.GetFieldType(i) == typeof(Boolean))
  {
      dataResult[i] = reader.GetBoolean(i).ToString();
  }
  else if (reader.GetFieldType(i) == typeof(Int64))
  {
      dataResult[i] = reader.getobj.GetInt64(i).ToString();
  }
  
     }
     
 }
 
 //Console.WriteLine("ID: " + reader.get.GetInt32(0));
 //Console.WriteLine("name: " + reader.GetString(1));
 //Console.WriteLine("email: " + reader.GetString(2));
    }
}
reader.Close();




隨著使用者輸入文字的多少,改變TextBox的形狀大小

private void textBox1_TextChanged(object sender, EventArgs e) {

 Size size = TextRenderer.MeasureText(textBox1.Text, textBox1.Font); 
 textBox1.Width = size.Width; textBox1.Height = size.Height; 

 }

參考
http://stackoverflow.com/questions/8048455/c-sharp-resize-textbox-to-fit-content

改變Textbox中的文字顏色

  • TextBox中的ForeColor屬性可以改變整個文字的顏色。
  • 要改變部分文字的顏色,只有使用RichTextBox控制項。選取要變色的文字,然後用SelectionColor屬性來改變所選取的文字顏色。

移除在Textbox中按下Enter鍵,會出現的嗶嗶聲

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)  
{  
    switch (e.KeyChar )  
    {  
 case '\r':  
     // perform necessary action  
     e.Handled = true;  
       
//do something  
//Run command  
     if (e.KeyCode.Equals(Keys.Enter))  
     {  
     }  
     break;  
   
    }  
}  

Textbox捲到最末行

//move the caret to the end of the text  
textBoxLog.SelectionStart = textBoxLog.TextLength;  
//scroll to the caret  
textBoxLog.ScrollToCaret();  

參考
http://stackoverflow.com/questions/1069497/how-to-scroll-down-in-a-textbox-by-code-in-c-sharp

C#使用Listview的Key


private void button1_Click(object sender, EventArgs e)   
{   
 for (int i = 0; i < 4; i++)   
 {   
  int test = i * i;   
  listView1.Items.Add("key" + i.ToString(), test.ToString(), i);   
 }   
}   
  
private void button2_Click(object sender, EventArgs e)   
{   
 for (int i = 0; i < 4; i++)   
 {   
  MessageBox.Show(listView1.Items["key" + i.ToString()].Text);   
 }   
} 
  

參考
http://zhidao.baidu.com/question/85025088

使用Thread

啟動Thread

Thread _runningThread =null;  
public void StartMainThread()  
{  
 try  
 {  
  if (_runningThread != null)  
  {  
   _runningThread.Abort();  
  }  
  _runningThread = new Thread(Go);     //也可以這樣寫_runningThread = new Thread(new ThreadStart(Go)); 
                _runningThread.IsBackground = true;  //設定thread在背景執行
  _runningThread.Start();  
 }  
 catch (Exception Ex)  
 {  
  Console.WriteLine(Ex.Message);  
 }  
}  

結束Thread

public void StopMainThread()  
{  
 try  
 {  
  if (_runningThread != null)  
  {  
   //stop Thread  
   _runningThread.Abort();  
   //Release resource  
   _runningThread = null;  
  }  
 }  
 catch (Exception Ex)  
 {  
  Console.WriteLine(Ex.Message);  
 }  
}  

Thread傳遞一個參數

Thread t = new Thread (new ParameterizedThreadStart (Go));  
t.Start (true);  
  
static void Go (object upperCase)  
{  
 bool upper = (bool) upperCase;  
 Console.WriteLine (upper ? "HELLO!" : "hello!");  
}  

Thread傳遞多個參數

方法一、使用委派

string words;  
string link;  
Thread _runningThread = new Thread(delegate() { Lookup(words, link); });  
_runningThread.Start(); 

方法一、使用類別

public class cc  
{  
 public int i;  
 public void ShowText()  
 {  
  i++;  
 }  
}   
  
private void button1_Click(object sender, System.EventArgs e)  
{  
 cc ac=new cc();  
 ac.i=0;  
 Thread a=new Thread(new ThreadStart(ac.ShowText));  
}  

設定處裡程序的記憶體大小

  • 成員宣告
    [DllImport("kernel32.dll")]
    
    static extern Boolean SetProcessWorkingSetSize(IntPtr procHandle, Int32 min, Int32 max);
    
  • 使用
    SetProcessWorkingSetSize(System.Diagnostics.Process.GetCurrentProcess().Handle, -1, -1);
    

將可用的字體新增到ComboBox控制項的項目中

comboBox1.Items.AddRange(FontFamily.Families); 

禁用TextBox控制項預設的選單

textBox1.ContextMenu=new ContextMenu();

不要將視窗標題顯示在任務欄上

將視窗的ShowIntaskbar屬性設為False就可以了。

為視窗設定一個默認按鈕與一個取消按鈕

form1.AcceptButton = button1; 
form1.CancelButton = button2; 

在.Net的Windows視窗中,啟用XP的佈景

  1. 將控制項的FlatStyle屬性改為System。
  2. 修改Main方法
    static void Main() 
    { 
        Application.EnableVisualStyles(); 
        Application.DoEvents(); 
        Application. Run(new Form1()); 
    } 
    

建立一個可以改變大小且沒有標題欄的視窗

form1.Text = string. Empty; 
form1.ControlBox = false; 

如何觸發Button的Click事件

button1.PerformClick();

在TextBox中可輸入多行文字

  • 利用TextBox控制項的Lines屬性
    string [] strAddress = {"Mukund Pujari","Global Transformation Technologies","Pune, India"}; 
    textBox1.MultiLine=true; 
    textBox1.Lines=strAddress; 
    
  • 或者
    textBox1.Text="Line 1\r\nLine2\r\nLine3."; 
    
    
  • 或者
    textBox1.Text="Line1"+System.Environment.NewLine+"Line2"+System.Environment.NewLine+"Line3";
    

2012年11月29日 星期四

generating random number and string

Author     Date Of Submission     User Level
Mahesh Chand    11/19/2004     Beginner



The Random class defined in the .NET Framework class library provides functionality to generate random numbers. 

 The Random class constructors have two overloaded forms. It takes either no value or it takes a seed value.

 The Random class has three public methods – Next, NextBytes, and NextDouble. The Next method returns a random number, NextBytes returns an array of bytes filled with random numbers, and NextDouble returns a random number between 0.0 and 1.0. The Next method has three overloaded forms and allows you to set the minimum and maximum range of the random number.

 The following code returns a random number:

 int num = random.Next();

 The following code returns a random number less than 1000.

 int num = random.Next(1000);

 The following code returns a random number between min and max:

 private int RandomNumber(int min, int max)
 {
Random random = new Random();
 return random.Next(min, max); 
 }

 At some point, you may also want to generate random strings. I have created a method, which takes first parameter as the size of string and second parameter if you want the string to be lowercase. 

 /// 
 /// Generates a random string with the given length
 /// 
 /// Size of the string
 /// If true, generate lowercase string
 /// Random string
 private string RandomString(int size, bool lowerCase)
 {
 StringBuilder builder = new StringBuilder();
Random random = new Random();
 char ch ;
 for(int i=0; i

generate ramdom list



using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {

            foreach (int tt in GenerateRandomList(1, 20))
            {
                Console.WriteLine(tt);
            }
            Console.ReadLine();
        }

        private static List GenerateRandomList(int min,int max)
        {
            Random rand = new Random();
            int index = 0;
            string str = string.Empty;
            List list = new List();
            List randList = new List();

            for (int j = min; j <= max; j++)
            {
                list.Add(j);
            }

            for (int i = 0; i < max; i++)
            {
                index = rand.Next(0, list.Count - 1);
                randList.Add (list[index]);
                list.RemoveAt(index);
            }
            return randList ;
        }
    }
}

format fileInfo length to KB


1. reference
using System.Globalization;

2. use this function
FormatSize(new FileInfo(fileName).length);
protected string FormatSize(long lSize)
        {
            //Format number to KB
            string stringSize = "";
            NumberFormatInfo myNfi = new NumberFormatInfo();

            long lKBSize = 0;

            if (lSize < 1024)
            {
                if (lSize == 0)
                {
                    //zero byte
                    stringSize = "0";
                }
                else
                {
                    //less than 1K but not zero byte
                    stringSize = "1";
                }
            }
            else
            {
                //convert to KB
                lKBSize = lSize / 1024;
                //format number with default format
                stringSize = lKBSize.ToString("n", myNfi);
                //remove decimal
                stringSize = stringSize.Replace(".00", "");
            }

            return stringSize + " KB";

        } 
張貼者: