C#项目开发小记

 //抓包工具

SmartSniff 1.77

 ////------------#region 截图
        private void toolStripButton6_Click(object sender, EventArgs e)
        {
            ScreenForm screen = new ScreenForm();
            screen.copytoFather += new CbRectangle(copytoTextBox);
            screen.ShowDialog();
        }

        /*截图后续操作*/
        public void copytoTextBox(Rectangle rec)
        {
            Rectangle rec2 = rec; //改造一下,去掉红色边框
            if (rec.Width > 2 && rec.Height > 2)
                rec2 = new Rectangle(rec.X + 1, rec.Y + 1, rec.Width - 2, rec.Height - 2);
            Rectangle r = Screen.PrimaryScreen.Bounds;
            Image img = new Bitmap(rec2.Width, rec2.Height);
            Graphics g = Graphics.FromImage(img);
            g.CopyFromScreen(rec2.Location, new Point(0, 0), rec2.Size);
            Clipboard.SetDataObject(img, false);
            this.exRichTextBox_send.Paste();
        }
        #endregion

 

//--------------------------------progressBar

public void SetProgress(int total, int transmitted)
        {
            if (this.InvokeRequired)
            {
                object[] args = { total, transmitted };
                this.Invoke(new CbSetProgress(this.SetProgress) ,args) ;
            }
            else
            {
                this.progressBar1.Maximum = total;
                this.progressBar1.Value   = transmitted;
                string str = ((double)transmitted*100/total).ToString();
                if (str.Length > 4)
                {
                    this.label_percent.Text = str.Substring(0, 4) + "%";
                }
                else
                {
                    this.label_percent.Text = str + "%";
                }

                if (this.progressBar1.Value == 0)
                {
                    this.lastDisplaySpeedTime = DateTime.Now;
                    this.lastTransmitted = transmitted;
                }
                else
                {
                    DateTime now = DateTime.Now;
                    TimeSpan span = now - this.lastDisplaySpeedTime;
                    if (span.TotalSeconds >= 1)
                    {
                        string unit = "K/s";
                        double speed = (transmitted - this.lastTransmitted) / 1000;
                        if (speed > 1000)
                        {
                            unit = "M/s";
                            speed = (int)speed / 10;
                            speed /= 100.0;
                        }
                        this.label_speed.Text = speed.ToString() + unit;
                        int leftSecs = (total - transmitted) / (transmitted - this.lastTransmitted);
                        int hour = leftSecs / 3600;
                        int min = (leftSecs % 3600) / 60;
                        int sec = ((leftSecs % 3600) % 60) % 60;
                        this.label_leftTime.Text = string.Format("{0}:{1}:{2}", hour.ToString("00"), min.ToString("00"), sec.ToString("00"));
                        this.lastDisplaySpeedTime = now;
                        this.lastTransmitted = transmitted;
                    }
                }

               
            }
        }

 

--------------------------//自定义泛型
  public class CustomList<T>:List<T> where T:class,IEnumerable
  {
  }

 --------------------------文件流读写操作------------------------------

 string path = Path.Combine(Application.StartupPath, "3.txt");
      //using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))
      //{
      //  using (StreamReader sr = new StreamReader(fs, Encoding.Default))
      //  {
      //    this.textBox1.Text=sr.ReadToEnd();
      //  }
      //}
      using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Write))
      {
        using (StreamWriter sr = new StreamWriter(fs, Encoding.UTF8))
        {
          sr.WriteLine("的事发生大富大上的fdfsdafjds fdsfj234234234");
        }
      }

 

----------------------接口映射-----------------------------

public class Man : IFlay, IRun
  {
    public string Flay(string name)
    {
      return name + ",飞!";
    }
    public string Run(string name)
    {
      return name + ",跑!";
    }
  }

 public interface IRun
  {
    string Run(string name);
  }

public interface IFlay
  {
    string Flay(string name);
  }

Man ma = new Man();
      if (ma is IFlay)
      {
        IFlay iFlay = ma as IFlay;//接口映射
        this.textBox1.Text=iFlay.Flay("人");
      }

-------------------------------枚举类型作为下列列表或入泛型方法-------------------------------

public static List<KeyValuePair<string, int>> GetKeyValuePairFromEnum<T>() where T : struct, IConvertible 

        { 

            List<KeyValuePair<string, int>> result = new List<KeyValuePair<string, int>>(); 

  

            IEnumerable<T> array = Enum.GetValues(typeof(T)).Cast<T>(); 

  

            foreach (T item in array) 

            { 

                string name = item.ToString(); 

                int value = (int)Enum.Parse(typeof(T), name); 

  

                KeyValuePair<string, int> pair = new KeyValuePair<string, int>(name, value); 

                result.Add(pair); 

            } 

  

            return result; 

        }

 

 

----------------------【装载】返回集合使用IEnumerable<>还是IList<>----------------------------------

这里要看你的具体需求,一般分为以下几种可能性:

1.如果你返回的集合是只用于遍历,不可修改的,则返回IEnumerable<T>

2.如果返回的集合需要修改,如添加和删除元素,用ICollection<T>

3.如果返回的集合需要支持排序,索引等,用IList<T>

4.如果返回的集合要支持索引,但不能添加,删除元素,用ReadOnlyCollection<T>

 

----------------------整型数组转换字符串---------------------

 

    string str = null;

int[] intArray = { 1, 2, 3, 4, 5, 6 };
      str = string.Join("|", Array.ConvertAll<int, string>(intArray,
      delegate(int i)
      {
        return i.ToString();
      }));

 

 

 

-------------------------http同步下载---------------------------

 

public static void DownLoadFileFromUrl(string url, string saveFilePath)
        {
            FileStream stream = new FileStream(saveFilePath, FileMode.Create, FileAccess.Write);
            WebRequest request = WebRequest.Create(url);
            try
            {
                WebResponse response = request.GetResponse();
                int contentLength = (int) response.ContentLength;
                byte[] buffer = new byte[1024];
                int count = 0;
                int num3 = 0;
                bool flag = false;
                while (!flag)
                {
                    count = response.GetResponseStream().Read(buffer, 0, buffer.Length);
                    if (count > 0)
                    {
                        stream.Write(buffer, 0, count);
                        num3 += count;
                    }
                    else
                    {
                        flag = true;
                    }
                }
                stream.Flush();
            }
            finally
            {
                stream.Close();
                request = null;
            }
        }

-------------------------http异步下载---------------------------

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
      //request.Method = WebRequestMethods.Http.Get
      request.BeginGetResponse(new AsyncCallback((IAsyncResult result) =>
      {
        HttpWebRequest httpWebRequest = (HttpWebRequest)result.AsyncState;
        using (HttpWebResponse response = (HttpWebResponse)httpWebRequest.EndGetResponse(result))
        {
          if (response.StatusCode == HttpStatusCode.OK)
          {
            string path = Path.Combine(Application.StartupPath, "1.jpg");
            using (FileStream writeStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Write))
            {
              using (Stream readStream = response.GetResponseStream())
              {
                int blockLength = 256 * 1024;
                byte[] byteBuffer = new byte[256 * 1024];
                int readLength = 0;
                while ((readLength = readStream.Read(byteBuffer, 0, blockLength)) > 0)
                {
                  writeStream.Write(byteBuffer, 0, readLength);
                  System.Threading.Thread.Sleep(10);
                }
              }
            }
          }
        }
      }), request);

 

-------------------------遍历枚举类型值及文本---------------------------

enum Color
  {
    Red=0,
    Green,
    Blue,
    Orange
  }

文本:

string[] eArray = Enum.GetNames(typeof(Color));
      foreach (string t in eArray)
      {
        eText += t + "  ";
      }

值:

string eValue = string.Empty;
      foreach (Color i in Enum.GetValues(typeof(Color)))
      {
        eValue += ((int)i).ToString() + "  ";
      }

 --------------------------------C#队列基本操作--------------------------------------

 

 List<UserInfo> userList = new List<UserInfo>
      {
        new UserInfo{Id=1,UserName="dd1",UserPwd="11"},
        new UserInfo{Id=2,UserName="dd2",UserPwd="22"},
        new UserInfo{Id=3,UserName="dd3",UserPwd="33"},
        new UserInfo{Id=4,UserName="dd4",UserPwd="44"},
        new UserInfo{Id=5,UserName="dd5",UserPwd="55"},
        new UserInfo{Id=6,UserName="dd6",UserPwd="66"},
        new UserInfo{Id=7,UserName="dd7",UserPwd="77"}
      };

      IEnumerable<UserInfo> ulst = new List<UserInfo>
      {
        new UserInfo{Id=8,UserName="dd8",UserPwd="88"},
        new UserInfo{Id=9,UserName="dd9",UserPwd="99"},
        new UserInfo{Id=10,UserName="dd10",UserPwd="1010"},
        new UserInfo{Id=11,UserName="dd11",UserPwd="1111"}
      };

      int length = userList.Count;
      length = length + 4;
      //Queue<UserInfo> qu = new Queue<UserInfo>(length);
      Queue<UserInfo> qu = new Queue<UserInfo>(ulst);
      foreach (UserInfo user in userList)
      {
        qu.Enqueue(user);//入队
      }

      for (int i = 0; i < length;i++)
      {
        UserInfo u = qu.Dequeue();//出队
        this.textBox1.Text +=length+"  "+ u.Id + System.Environment.NewLine;
      }

 

-------------------------------常用的集合类和由这些类实现的集合接口----------------------------------

 

  • 集合及其实现的接口一览

下面罗列出来较为常用的集合类和由这些类实现的集合接口:

集合类

集合接口

ArrayList

IList, ICollection,IEnumerable

Queue

ICollection,IEnumerable

Stack

ICollection,IEnumerable

BitArray

ICollection,IEnumerable

Hashtable

IDictionary,ICollection,IEnumerable

SortedList

IDictionary,ICollection,IEnumerable

List<T>

IList<T>,ICollection<T>,IEnumerable<T>,IList,ICollection,IEnumerable

Queue<T>

IEnumerable<T>,ICollection,IEnumerable

Stack<T>

IEnumerable<T>,ICollection,IEnumerable

LinkedList<T>

IEnumerable<T>,ICollection<T>,ICollection,IEnumerable

HashSet<T>

IEnumerable<T>,ICollection<T>,IEnumerable

Dictionary<TKey, TValue>

IDictionary<TKey, TValue>,

ICollection<KeyValuePair<TKey, TValue>>,

IEnumerable<KeyValuePair<TKey, TValue>>,

IDictionary,ICollection,IEnumerable

SortedDictionary<TKey, TValue>

IDictionary<TKey, TValue>,

ICollection<KeyValuePair<TKey, TValue>>,

IEnumerable<KeyValuePair<TKey, TValue>>,

IDictionary,ICollection,IEnumerable

SortedList<TKey, TValue>

IDictionary<TKey, TValue>,

ICollection<KeyValuePair<TKey, TValue>>,

IEnumerable<KeyValuePair<TKey, TValue>>,

IDictionary,ICollection,IEnumerable

Lookup<TKey, TElement>

LKoopup<TKey, TElement>,

IEnumerable<IGrouping<TKey, TElemet>>,IEnumerable

-----------------------遍历Form应用程序目录--------------------------

 string directory = System.IO.Directory.GetParent(System.Windows.Forms.Application.ExecutablePath).FullName;
            this.addinManagement.LoadAllAddins(directory, true);

            foreach (IAddin addin in this.addinManagement.AddinList)
            {
                IPassiveAddin passiveAddin = addin as IPassiveAddin;
                if (passiveAddin != null)
                {
                    ToolStripItem item = new ToolStripMenuItem(passiveAddin.ServiceName, null, new EventHandler(this.OnAddinMenuClicked));
                    item.Tag = passiveAddin;
                    this.lIToolStripMenuItem_addin.DropDownItems.Add(item);

                    this.xImageListBox1.AddItem(passiveAddin.ServiceName, 6, passiveAddin);
                }
            }

 

posted @ 2011-10-26 14:36  火腿骑士  阅读(295)  评论(0编辑  收藏  举报