1.操作文件夹
1)获取当前程序路径
string str = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
str.Replace("\"", "");
int ind = str.LastIndexOf("\\");
localPath = str.Substring(0,ind);
获取当前程序的安装路径时,先获取当前程序的完整名,然后取最后一个“\”之前的子字符串即为当前路径。
2)打开文件夹,并选中文件
System.Diagnostics.Process.Start("Explorer.exe", localPath);//打开localPath
当需要选中该路径下的某个文件需要用select命令:
System.Diagnostics.Process.Start("Explorer.exe","/select," + localPath+ "\\Start.exe");//打开local以后选中目录下的start.exe文件
2.操作收藏夹
这里讲的收藏夹不是用户浏览器的Favorite,而是Links,可以理解为快捷方式。操作收藏夹需要用到快捷方式,因此添加COM引用---Windows Script Host Object Model
添加组件后,相当于添加IWshRuntimeLibrary程序集。
using IWshRuntimeLibrary;
string shortcutName = "Mylink.lnk";
//实例化WshShell对象
//通过该对象的 CreateShortcut 方法来创建 IWshShortcut 接口的实例对象
string userDir = Environment.GetEnvironmentVariable(@"USERPROFILE");
string Lpath = System.IO.Path.Combine(userDir+"\\Links",shortcutName);
WshShell shell = new WshShell();
IWshShortcut shortcut = (IWshShortcut)shell.CreateShortcut(Lpath);
//设置快捷方式的目标所在的位置,path代表Links链接的位置
shortcut.TargetPath = path;
//应用程序的工作目录
//当用户没有指定一个具体的目录时,快捷方式的目标应用程序将使用该属性所指定的目录来装载或保存文件。
shortcut.WorkingDirectory = System.Environment.CurrentDirectory;
//快捷方式的描述
shortcut.Save();
以上代码会在如上位置生成一个名为MyLink的快捷方式,链接到path路径下。
3.操作库
操纵库,需要到微软网站上下载一个SDK http://archive.msdn.microsoft.com/WindowsAPICodePack/Release/ProjectReleases.aspx?ReleaseId=4906,下载之后把Microsoft.WindowsAPICodePack.dll 和 Microsoft.WindowsAPICodePack.Shell.dll添加进工程即可。
代码如下:
static void LibraryDemo()
{
string libraryName = "我的库";
string windowFolder = @"C:\Windows";
string programFolder = @"C:\Program Files";
ShellLibrary library = new ShellLibrary(libraryName, true); // 第二个参数overwrite表示是否覆盖原有的库
library.Add(windowFolder); // 添加一个目录
library.Remove(windowFolder); // 删除一个已有目录
library.Add(windowFolder); // 折腾一下,再添加回来
library.Add(programFolder);
string defaultSaveFolderPath = library.DefaultSaveFolder; // 默认保存到的文件夹,是第一个添加进库的目录
library.DefaultSaveFolder = programFolder;// 更改默认保存到的文件夹
library.IconResourceId = new IconReference(Assembly.GetExecutingAssembly().Location, -32512);
ShellLibrary lib = ShellLibrary.Load(libraryName, true); // 第二个参数isReadOnly表示是否允许改动库
}
改代码在如下路径出添加一个叫“我的库”的库
上面的程序需要用到图标,所以在项目的属性页里给程序添加一个图标。