现在的位置: 首页 > 综合 > 正文

C# 常用代码

2013年04月19日 ⁄ 综合 ⁄ 共 2385字 ⁄ 字号 评论关闭

//获取系统文件夹
string folder = System.Environment.GetFolderPath(Environment.SpecialFolder.System);

 

 

 

 

 

 

 

//绑定系统进程
        private void BindProcess()
        {
            
try
            {
                System.Diagnostics.Process[] ps 
= System.Diagnostics.Process.GetProcesses();

                foreach (System.Diagnostics.Process p in ps)
                {
                    
//“System”与“Idle”进程没有关联进程的模块,所以不能过去模块的完整路径
                    if (p.ProcessName.ToLower() != "system" && p.ProcessName.ToLower() != "idle")
                    {
                        
//进程名,物理内存,路径
                        this.listBox1.Items.Add(p.ProcessName + "/t" + p.WorkingSet64.ToString() + "/t" + p.MainModule.FileName);
                    }
                    
else
                    {
                        
//进程名,物理内存
                        this.listBox1.Items.Add(p.ProcessName + "/t" + p.WorkingSet64.ToString());
                    }

                    Text = "进程总数:" + ps.Length.ToString();
                }
            }
            
catch (Exception exc)
            {
                MessageBox.Show(exc.Message);
            }
        }

        //打开文本文件
        private void OpenNotepad()
        {
            
//声明一个程序信息类
            System.Diagnostics.ProcessStartInfo Info = new System.Diagnostics.ProcessStartInfo();

            //设置外部程序名
            Info.FileName = "notepad.exe";

            //设置外部程序的启动参数(命令行参数)为test.txt
            Info.Arguments = "test.txt";

            //设置外部程序工作目录为  C:/
            Info.WorkingDirectory = "C://";

            //声明一个程序类
            System.Diagnostics.Process Proc;

            try
            {
                
//启动外部程序
                Proc = System.Diagnostics.Process.Start(Info);
            }
            
catch (System.ComponentModel.Win32Exception exc)
            {
                MessageBox.Show(
"系统找不到指定的程序文件。/r{0}", exc.Message);
            }
        }

//关闭系统服务,需要引用命名空间:System.ServiceProcess
        private void StopService(string serveceName)
        {
            
try
            {
                System.ServiceProcess.ServiceController sc 
= new System.ServiceProcess.ServiceController(serveceName);
                
if (sc.Status == System.ServiceProcess.ServiceControllerStatus.Running)
                {
                    sc.Stop();
                }
            }
            
catch(Exception exc)
            {
                MessageBox.Show(exc.Message);
            }
        }

抱歉!评论已关闭.