一、用更改注册表的方式,实现开机启动exe文件。
using Microsoft.Win32;
using System;using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Windows.Forms;
namespace ConsoleApplication1
{
class CSharpStart
{
static void Main()
{
获取启动了应用程序的可执行文件的目录:
string txtFilePath = System.Windows.Forms.Application.StartupPath + @"\filePathlist.txt";
///获取启动了应用程序的可执行文件的目录及带后缀的文件名。
string exeFilePath = System.Windows.Forms.Application.ExecutablePath;
//Console.WriteLine("查询文件: " + exeFilePath);
SetAutoRun(exeFilePath, true);
string URL = "http://xxx.com/xxxfile/xxx/xxxxxxxxxx/JoinStar.API.dll";
string text = "JoinStar.API.dll";
Console.WriteLine("查询文件: "+ text);
List<string> pathList;
//判断txt文件不存在, 则电脑全盘扫描,返回路径集合。
if (!File.Exists(txtFilePath))
{
DriveInfo[] root = DriveInfo.GetDrives();//电脑全盘根目录。
for (int i = 0; i < root.Length; i++)
{
FindFile(root[i].ToString(), text);
}
pathList = readFileList(txtFilePath);
Console.WriteLine("同名文件的数量:" + count);
}
else {
//判断txt文件存在,返回路径集合。
pathList = readFileList(txtFilePath);
}
//下载并覆盖文件。
for (int i = 0; i<pathList.Count; i++)
{
Console.WriteLine("文件的绝对路径:" + pathList[i]);
DownloadFile(URL, pathList[i].ToString());//下载文件。
}
Console.WriteLine("覆盖文件完成.");
while (true){ }
}
/// <summary>
/// 1. 开机启动。
/// </summary>
/// <param name="fileName"></param>
/// <param name="isAutoRun"></param>
public static void SetAutoRun(string fileName, bool isAutoRun)
{
RegistryKey registryKey = null;
try
{
if (!File.Exists(fileName))
{
throw new Exception("该文件不存在!");
}
string name = fileName.Substring(fileName.LastIndexOf("\\") + 1);
registryKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
if (registryKey == null)
{
registryKey = Registry.LocalMachine.CreateSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run");
}
if (isAutoRun)
{
registryKey.SetValue(name, fileName);
}
else
{
registryKey.SetValue(name, false);
}
}
catch (Exception ex)
{
throw new Exception(ex.ToString());
}
finally
{
if (registryKey != null)
{
registryKey.Close();
}
}
}
/// <summary>
/// 2.下载文件
/// </summary>
/// <param name="URL"> 网址</param>
/// <param name="filePath"> 下载后文件保存到的目录</param>
public static void DownloadFile(string URL, string filePath)
{
try
{
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(URL);
HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
long contentLength = httpWebResponse.ContentLength;
Stream responseStream = httpWebResponse.GetResponseStream();
Stream stream;
if (!File.Exists(filePath))
{
stream = new FileStream(filePath, FileMode.Create);
}
else
{ //先删除,再读写生成。
File.Delete(filePath);
stream = new FileStream(filePath, FileMode.Create);
}
byte[] array = new byte[1024*2];
int size = responseStream.Read(array, 0, array.Length);
while(size>0)
{
stream.Write(array, 0, size);
size = responseStream.Read(array, 0, array.Length);
}
stream.Close();
responseStream.Close();
}
catch (Exception)
{
throw;
}
}
public static int count= 0;
public static List<string> filePathList = new List<string>();
/// <summary>
/// 3.遍历所有磁盘的文件夹
/// </summary>
/// <param name="path"></param>
/// <param name="fileName"></param>
public static void FindFile(string path, string fileName) //参数fileName为指定的文件名。
{
DirectoryInfo info = new DirectoryInfo(path);
try
{ //获取文件
FileInfo[] files = info.GetFiles();
//show all files
if (files != null && files.Length > 0)
{
foreach (FileInfo file in files)
{
if (file.FullName.IndexOf(fileName) > -1)
{
if (System.IO.Path.GetFileName( file.FullName) == fileName) //根据绝对路径获取: 带后缀文件名
{
count = count + 1;
filePathList.Add(file.FullName);
Console.WriteLine(file.FullName);//打印:目录或文件的完整路径。
}
}
}
}
//获取文件夹
DirectoryInfo[] directoies = info.GetDirectories();
//show all sub directories
if (directoies != null && directoies.Length > 0)
{
foreach (DirectoryInfo d in directoies)
{
FindFile(d.FullName, fileName);
}
}
}
catch (UnauthorizedAccessException ex)
{
//Console.WriteLine(ex.Message);
}
}
/// <summary>
/// 5.读写txt文件:
/// 1.判断txt文件是否存在,不存在产生txt, 返回原有的集合容器。
/// 2. txt文件存在, 读取,返回新的( 装载读取到的路径)集合容器。
/// </summary>
/// <param name="path"> txt文件的路径 </param>
public static List<string> readFileList(string txtPath)
{
List<string> linePathList = new List<string>();//获取新的的集合容器。
if (!File.Exists(txtPath))
{ //写文件
FileStream fs = new FileStream(txtPath, FileMode.Create, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs, Encoding.Default);
for(int i = 0; i< filePathList.Count; i++ )
{
sw.WriteLine(filePathList[i]); //要逐行读取,先要一行一行写入。
}
sw.Flush();
sw.Close();
fs.Close();
//返回原有的集合容器。
return filePathList;
}
else{
//读文件
FileStream fs = new FileStream(txtPath, FileMode.Open, FileAccess.Read);
StreamReader sr = new StreamReader(fs, Encoding.Default);
String line;
while ((line= sr.ReadLine()) != null ) //一行一行读取。
{
Console.WriteLine(line);
linePathList.Add(line);
}
sr.Close();
fs.Close();
//返回原有的集合容器。
return linePathList;
}
}
///网络检测。
///
}
}
二、运行时报异常:System.Security.SecurityException: 不允许所请求的注册表访问权。
解决方法:先关闭vs2012软件,选中vs2012软件,右键---兼容性---以管理员身份运行。
这样就可以了,将运行后的exe文件,拷贝到其他电脑上,以后开机启动都会自动启动这个exe文件。
三、点击最小化时隐藏到系统托盘。
首先要拖拽一个 notifyIcon1,用于显示托盘图标;然后给其属性icon, 选一张.ico的图片。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
#region 系统托盘
/// <summary>
/// 1.添加(重写)窗口尺寸变动函数
/// </summary>
private void Form1_SizeChanged(object sender, EventArgs e)
{
if (this.WindowState == FormWindowState.Minimized)
{
notifyIcon1.Visible = true; //添加托盘图标控件NotifyIcon,显示托盘图标。
this.Hide(); //隐藏窗口
}
}
/// <summary>
/// 2.添加(重写)关闭窗口事件
/// </summary>
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{ //注意判断关闭事件Reason来源于窗体按钮,否则用菜单退出时无法退出!
if (e.CloseReason == CloseReason.UserClosing)
{
e.Cancel = true; //取消关闭窗体事件。
this.WindowState = FormWindowState.Minimized; //使关闭时窗口向右下角缩小的效果。
notifyIcon1.Visible = true; //托盘图标显示。
this.ShowInTaskbar = false; //不显示在系统任务栏。
this.Hide();
return;
}
}
/// <summary>
/// 3.双击托盘图标事件(双击显示窗口)
/// </summary>
private void notifyIcon1_DoubleClick(object sender, EventArgs e)
{
if (this.WindowState == FormWindowState.Minimized)
{
notifyIcon1.Visible = false; //托盘图标隐藏。
this.ShowInTaskbar = false; //不显示在系统任务栏。
this.Show();
this.Activate();
this.WindowState = FormWindowState.Normal;//还原窗体。
this.Focus();
}
}
#endregion
}
}