67.创建目录副本整合操作
/*
using System.IO;
using System.Collections;
*/
FolderDialog aa = new FolderDialog();
aa.DisplayDialog();
bool b = MessageBox.Show("是否也创建空文件?", "构建文件夹框架", MessageBoxButtons.OKCancel, MessageBoxIcon.Information) == DialogResult.OK ? true : false;
if (aa.Path != "")
{
string path = (aa.Path.LastIndexOf(Path.DirectorySeparatorChar) == aa.Path.Length - 1) ? aa.Path : aa.Path + Path.DirectorySeparatorChar;
string parent = Path.GetDirectoryName(%%1);
Directory.CreateDirectory(path + Path.GetFileName(%%1));
%%1 = (%%1.LastIndexOf(Path.DirectorySeparatorChar) == %%1.Length - 1) ? %%1 : %%1 + Path.DirectorySeparatorChar;
DirectoryInfo dir = new DirectoryInfo(%%1);
FileSystemInfo[] fileArr = dir.GetFileSystemInfos();
Queue<FileSystemInfo> Folders = new Queue<FileSystemInfo>(dir.GetFileSystemInfos());
while (Folders.Count > 0)
{
FileSystemInfo tmp = Folders.Dequeue();
FileInfo f = tmp as FileInfo;
if (f == null)
{
DirectoryInfo d = tmp as DirectoryInfo;
Directory.CreateDirectory(d.FullName.Replace((parent.LastIndexOf(Path.DirectorySeparatorChar) == parent.Length - 1) ? parent : parent + Path.DirectorySeparatorChar, path));
foreach (FileSystemInfo fi in d.GetFileSystemInfos())
{
Folders.Enqueue(fi);
}
}
else
{
if(b) File.Create(f.FullName.Replace(parent, path));
}
}
}

68.打开网页
//System.Diagnostics;
Process.Start(@"C:\Program Files\Internet Explorer\iexplore.exe", %%1); //"http://ant.sourceforge.net/"

69.删除空文件夹整合操作
//using System.IO;
FolderDialog aa = new FolderDialog();
aa.DisplayDialog();
if (aa.Path != "")
{
string path = aa.Path;
DirectoryInfo dir = new DirectoryInfo(aa.Path);
FileSystemInfo[] fileArr = dir.GetFileSystemInfos();
Queue<String> Folders = new Queue<String>(Directory.GetDirectories(aa.Path));
while (Folders.Count > 0)
{
path = Folders.Dequeue();
string[] dirs = Directory.GetDirectories(path);
try
{
Directory.Delete(path);
}
catch (Exception)
{
foreach (string direct in dirs)
{
Folders.Enqueue(direct);
}
}
}
}

70.获取磁盘所有分区,把结果放在数组drives中
//using System.IO;
DriveInfo[] drives = DriveInfo.GetDrives();

71.激活一个程序或程序关联的文件
//using System.Diagnostics;
Process LandFileDivisison;
LandFileDivisison = new System.Diagnostics.Process();
LandFileDivisison.StartInfo.FileName = %%1;
LandFileDivisison.Start();

72.MP3播放
/*
using System.Runtime.InteropServices;
public static uint SND_ASYNC = 0x0001; // play asynchronously
public static uint SND_FILENAME = 0x00020000; // name is file name
[DllImport("winmm.dll")]
public static extern int mciSendString(string m_strCmd, string m_strReceive, int m_v1, int m_v2);
[DllImport("Kernel32", CharSet = CharSet.Auto)]
static extern Int32 GetShortPathName(String path,StringBuilder shortPath, Int32 shortPathLength);
*/
string name = %%1
StringBuilder shortpath=new StringBuilder(80);
int result=GetShortPathName(name,shortpath,shortpath.Capacity);
name=shortpath.ToString();
mciSendString(@"close all",null,0,0);
mciSendString(@"open "+name+" alias song",null,0,0); //打开
mciSendString("play song",null,0,0); //播放

73.WAV播放
/*
using System.Runtime.InteropServices;
public static uint SND_ASYNC = 0x0001; // play asynchronously
public static uint SND_FILENAME = 0x00020000; // name is file name
[DllImport("winmm.dll")]
public static extern int mciSendString(string m_strCmd, string m_strReceive, int m_v1, int m_v2);
[DllImport("Kernel32", CharSet = CharSet.Auto)]
static extern Int32 GetShortPathName(String path,StringBuilder shortPath, Int32 shortPathLength);
*/
string name = %%1
StringBuilder shortpath=new StringBuilder(80);
int result=GetShortPathName(name,shortpath,shortpath.Capacity);
name=shortpath.ToString();
mciSendString(@"close all",null,0,0);
mciSendString(@"open "+name+" alias song",null,0,0); //打开
mciSendString("play song",null,0,0); //播放


74.写图像到剪切板
//using System.IO;
Bitmap bm =new Bitmap(filename);
Clipboard.SetDataObject(bm,true);

75.从剪贴板复制图像到窗体
if (Clipboard.ContainsImage())
{
this.pictureBox1.Image = Clipboard.GetImage();
}
剪贴板中的数据类型
//using System.IO;
d.GetDataPresent(DataFormats.Bitmap)//(.Text .Html)
Bitmap b = (Bitmap)d.GetData(DataFormat Bitmap)
粘贴
IDataObject data = Clipboard.GetDataObjects;
if(Data.GetDataPresent(DataFormats.Bipmap))
{
b.Save(@"C:\mymap.bmp");
}

76.删除文件夹下的所有文件且不删除文件夹下的文件夹
//using System.IO;

77.XML遍历结点属性值
//using System.IO;

78.Unicode文件转GB2312格式
/*
using System.IO;
using System.Text;
*/
File.WriteAllText(%%2, File.ReadAllText(%%1,Encoding.Unicode), Encoding.GetEncoding("GB2312"));

79.开源程序库Xercesc-C++代码工程中内联
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Text;

public class InlineXercesc
{
private const String filter = ".cpp";
private ArrayList all = new ArrayList();
private Queue<String> fal2 = new Queue<String>();
private static String CurDir = Environment.CurrentDirectory;
public InlineXercesc(String lib)
{
string SourceLib = "D:\\Desktop\\大项目\\xerces-c-3.0.1\\src";
string pattern = "include.*?" + lib + ".*?>"; // 第一个参数为需要匹配的字符串
Match matcher = null;
Queue<string> fal = new Queue<string>();
DirectoryInfo delfile = new DirectoryInfo(CurDir);
foreach (DirectoryInfo files2 in delfile.GetDirectories())
{
String enumDir = CurDir + Path.DirectorySeparatorChar + files2.Name + Path.DirectorySeparatorChar;
FileSystemInfo[] fileArr = files2.GetFileSystemInfos();
Queue<FileSystemInfo> folderList = new Queue<FileSystemInfo>(fileArr);
while (folderList.Count > 0)
{
FileSystemInfo tmp = folderList.Dequeue();
FileInfo f = tmp as FileInfo;
if (f == null)
{
DirectoryInfo d = tmp as DirectoryInfo;
foreach (FileSystemInfo fi in d.GetFileSystemInfos())
{
folderList.Enqueue(fi);
}
}
else
{
StreamReader br = null;
try
{
br = new StreamReader(file);
// 打开文件
}
catch (IOException e)
{
// 没有打开文件,则产生异常
System.Console.Error.WriteLine("Cannot read '" + f.FullName + "': " + e.Message);
continue;
}
String line;
StringBuilder sb = new StringBuilder(2048);
while ((line = br.ReadLine()) != null)
{
// 读入一行,直到文件结束
matcher = Regex.Match(line, pattern); // 匹配字符串
if (matcher.Success == true)
{
// 如果有匹配的字符串,则输出
sb.Append(line.Replace(line.Substring(line.IndexOf("<"), (line.LastIndexOf("/") + 1) - (line.IndexOf("<"))), "\"").Replace('>', '\"'));
line = line.Substring(line.IndexOf("<") + 1, (line.LastIndexOf(">")) - (line.IndexOf("<") + 1)).Replace('/', '\\');
fal.Enqueue(SourceLib + Path.DirectorySeparatorChar + line);
}
else
{
sb.Append(line);
}
sb.Append("\r\n");
}
br.Close(); // 关闭文件
StreamWriter w = new StreamWriter(f.FullName);
w.WriteLine(sb.ToString());
w.Close();
}
}
while (fal.Count > 0)
{
String file = fal.Dequeue(); // 第2个参数开始,均为文件名。
String targetPath = enumDir + file.Substring(file.LastIndexOf(Path.DirectorySeparatorChar) + 1);
if (targetPath.IndexOf('<') == -1 && !!File.Exists(targetPath))
{
File.CreateText(targetPath);
StreamReader br = null;
String line;
try
{
br = new StreamReader(new StreamReader(file).BaseStream, System.Text.Encoding.UTF7);
// 打开文件
}
catch (IOException e)
{
// 没有打开文件,则产生异常
//UPGRADE_TODO: 在 .NET 中,method 'java.lang.Throwable.getMessage' 的等效项可能返回不同的值。. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1043"'
System.Console.Error.WriteLine("Cannot read '" + file + "': " + e.Message);
continue;
}
StreamWriter fw = new StreamWriter(targetPath);
while ((line = br.ReadLine()) != null)
{
// 读入一行,直到文件结束
matcher = Regex.Match(line, pattern); // 匹配字符串
if (matcher.Success == true)
{
// 如果有匹配的字符串,则输出
fal.Enqueue(SourceLib + Path.DirectorySeparatorChar + line.Substring(line.IndexOf("<") + 1, (line.LastIndexOf(">")) - (line.IndexOf("<") + 1)).Replace('/', '\\'));
line = line.Replace(line.Substring(line.IndexOf("<"), (line.LastIndexOf("/") + 1) - (line.IndexOf("<"))), "\"");
line = line.Replace(">", "\"");
}
fw.Write(line + "\r\n");
}
fw.Flush();
fw.Close();
br.Close(); // 关闭文件
}
}
Queue<string> folderListArr = new Queue<string>();
folderListArr.Enqueue(CurDir);
while (folderListArr.Count > 0)
{
DirectoryInfo file = new DirectoryInfo(folderListArr.Dequeue());
FileSystemInfo[] files = file.GetFileSystemInfos();
for (int i = 0; i < files.Length; i++)
{
DirectoryInfo ddd = files[i] as DirectoryInfo;
if (ddd != null)
{
folderListArr.Enqueue(files[i].FullName);
}
else
{
if (files[i].Extension == ".hpp")
{
all.Add(files[i].FullName.Replace(".hpp", ".cpp"));
}
}
}
}
int count = 1;
while (count > 0)
{
doSearch(SourceLib);
all.Clear();
while (fal2.Count > 0)
{
String file1 = fal2.Dequeue(); // 第2个参数开始,均为文件名。
String targetPath = enumDir + file1.Substring(file1.LastIndexOf(Path.DirectorySeparatorChar) + 1);
if (targetPath.IndexOf('<') == -1 && !File.Exists(targetPath))
{
File.CreateText(targetPath);
StreamReader br = null;
String line;
try
{
br = new StreamReader(file1);
// 打开文件
}
catch (IOException e)
{
System.Console.Error.WriteLine("Cannot read '" + file1 + "': " + e.Message);
continue;
}
StreamWriter fw;
try
{
fw = new StreamWriter(targetPath);
while ((line = br.ReadLine()) != null)
{
// 读入一行,直到文件结束
matcher = Regex.Match(line, pattern); // 匹配字符串
if (matcher.Success == true)
{
// 如果有匹配的字符串,则输出
fal2.Enqueue(SourceLib + Path.DirectorySeparatorChar + line.Substring(line.IndexOf('<') + 1, (line.LastIndexOf('>')) - (line.IndexOf('<') + 1)).Replace('/', '\\'));
all.Add(fal2.Peek().Replace(".hpp", ".cpp"));
line = line.Replace(line.Substring(line.IndexOf('<'), (line.LastIndexOf('/') + 1) - (line.IndexOf('<'))), "\"");
line = line.Replace('>', '\"');
}
fw.Write(line + "\r\n");
}
fw.Flush();
fw.Close();
br.Close(); // 关闭文件
}
catch (IOException e)
{
Console.Error.WriteLine(e.StackTrace);
}
}
}
count = all.Count;
}
}
}

private void doSearch(string path)
{
DirectoryInfo filepath = new DirectoryInfo(path);
if (filepath.Exists)
{

FileSystemInfo[] fileArray = filepath.GetFileSystemInfos();
foreach (FileSystemInfo f in fileArray)
{
DirectoryInfo dd = f as DirectoryInfo;
if (dd != null)
{
doSearch(f.FullName);
}
else
{
FileInfo ff = f as FileInfo;
if (f.Name.IndexOf(filter) > -1)
{
foreach (string file in all)
{
if (file.IndexOf('<') == -1 && Path.GetFileName(file) == f.Name)
{
fal2.Enqueue(f.FullName);
}
}
}
}
}
}
}
static void Main(String[] args)
{
new InlineXercesc("xercesc");
FileInfo f = new FileInfo(CurDir + "\\DetailCpp.cmd");
StreamWriter w = f.CreateText();
w.WriteLine("copy StdAfx.cpp+*.c+*.cpp " + CurDir
+ "\\StdAfx.cpp && del *.c && del *.cpp");
w.Close();
}
}

80.提取包含头文件列表
//InlineExt.cs
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Text;

public class InlineExt
{
private System.String CurDir = Environment.CurrentDirectory;
public InlineExt()
{
string pattern = "include.*?\".*?.hpp\""; // 第一个参数为需要匹配的字符串
Match matcher = null;
FileInfo delfile = new System.IO.FileInfo(CurDir);
FileInfo[] files2 = SupportClass.FileSupport.GetFiles(delfile);
for (int l = 0; l < files2.Length; l++)
{
if (Directory.Exists(files2[l].FullName))
{
Queue<String> ts = new Queue<String>();
FileInfo file = new FileInfo(Path.Combine(files2[l].FullName , "StdAfx.cpp"));
StreamReader br = null;
StreamWriter fw = null;
String line;
try
{
br = new StreamReader(new StreamReader(file.FullName, System.Text.Encoding.Default).BaseStream, new System.IO.StreamReader(file.FullName, System.Text.Encoding.Default).CurrentEncoding); // 打开文件
while ((line = br.ReadLine()) != null)
{
matcher = Regex.Match(line, pattern); // 匹配字符串
if (matcher.Success == true)
{
// 如果有匹配的字符串,则输出
ts.Enqueue(line.Substring(line.IndexOf('\"') + 1, (line.LastIndexOf('\"')) - (line.IndexOf('\"') + 1)));
}
}
FileInfo file2 = new FileInfo(Path.Combine(files2[l].FullName , "ReadMe.txt"));
if (File.Exists(file2.FullName))
{
fw = new StreamWriter(file2.FullName, false, System.Text.Encoding.GetEncoding("GB2312")); //System.Text.Encoding.Default
foreach(string it in ts)
{
fw.Write("#include \"" + it + "\"\r\n");
}
}
}
catch (IOException e)
{
// 没有打开文件,则产生异常
Console.Error.WriteLine("Cannot read '" + file + "': " + e.Message);
continue;
}
finally
{
try
{
if (br != null)
br.Close();
if (fw != null)
fw.Close();
}
catch (IOException e)
{
Console.WriteLine(e.StackTrace);
}
}
}
}
}
public static void Main(System.String[] args)
{
new InlineExt();
}
}

//SupportClass.cs
using System;
/// <summary>
/// Contains conversion support elements such as classes, interfaces and static methods.
/// </summary>
public class SupportClass
{
/// <summary>
/// Writes the exception stack trace to the received stream
/// </summary>
/// <param name="throwable">Exception to obtain information from</param>
/// <param name="stream">Output sream used to write to</param>
public static void WriteStackTrace(System.Exception throwable, System.IO.TextWriter stream)
{
stream.Write(throwable.StackTrace);
stream.Flush();
}
/*******************************/
/// <summary>
/// Represents the methods to support some operations over files.
/// </summary>
public class FileSupport
{
/// <summary>
/// Creates a new empty file with the specified pathname.
/// </summary>
/// <param name="path">The abstract pathname of the file</param>
/// <returns>True if the file does not exist and was succesfully created</returns>
public static bool CreateNewFile(System.IO.FileInfo path)
{
if (path.Exists)
{
return false;
}
else
{
System.IO.FileStream createdFile = path.Create();
createdFile.Close();
return true;
}
}
/// <summary>
/// Compares the specified object with the specified path
/// </summary>
/// <param name="path">An abstract pathname to compare with</param>
/// <param name="file">An object to compare with the given pathname</param>
/// <returns>A value indicating a lexicographically comparison of the parameters</returns>
public static int CompareTo(System.IO.FileInfo path, System.Object file)
{
if( file is System.IO.FileInfo )
{
System.IO.FileInfo fileInfo = (System.IO.FileInfo)file;
return path.FullName.CompareTo( fileInfo.FullName );
}
else
{
throw new System.InvalidCastException();
}
}
/// <summary>
/// Returns an array of abstract pathnames representing the files and directories of the specified path.
/// </summary>
/// <param name="path">The abstract pathname to list it childs.</param>
/// <returns>An array of abstract pathnames childs of the path specified or null if the path is not a directory</returns>
public static System.IO.FileInfo[] GetFiles(System.IO.FileInfo path)
{
if ( (path.Attributes & System.IO.FileAttributes.Directory) > 0 )
{
String[] fullpathnames = System.IO.Directory.GetFileSystemEntries(path.FullName);
System.IO.FileInfo[] result = new System.IO.FileInfo[fullpathnames.Length];
for(int i = 0; i < result.Length ; i++)
result[i] = new System.IO.FileInfo(fullpathnames[i]);
return result;
}
else return null;
}
/// <summary>
/// Creates an instance of System.Uri class with the pech specified
/// </summary>
/// <param name="path">The abstract path name to create the Uri</param>
/// <returns>A System.Uri instance constructed with the specified path</returns>
public static System.Uri ToUri(System.IO.FileInfo path)
{
System.UriBuilder uri = new System.UriBuilder();
uri.Path = path.FullName;
uri.Host = String.Empty;
uri.Scheme = System.Uri.UriSchemeFile;
return uri.Uri;
}
/// <summary>
/// Returns true if the file specified by the pathname is a hidden file.
/// </summary>
/// <param name="file">The abstract pathname of the file to test</param>
/// <returns>True if the file is hidden, false otherwise</returns>
public static bool IsHidden(System.IO.FileInfo file)
{
return ((file.Attributes & System.IO.FileAttributes.Hidden) > 0);
}
/// <summary>
/// Sets the read-only property of the file to true.
/// </summary>
/// <param name="file">The abstract path name of the file to modify</param>
public static bool SetReadOnly(System.IO.FileInfo file)
{
try
{
file.Attributes = file.Attributes | System.IO.FileAttributes.ReadOnly;
return true;
}
catch (System.Exception exception)
{
String exceptionMessage = exception.Message;
return false;
}
}
/// <summary>
/// Sets the last modified time of the specified file with the specified value.
/// </summary>
/// <param name="file">The file to change it last-modified time</param>
/// <param name="date">Total number of miliseconds since January 1, 1970 (new last-modified time)</param>
/// <returns>True if the operation succeeded, false otherwise</returns>
public static bool SetLastModified(System.IO.FileInfo file, long date)
{
try
{
long valueConstant = (new System.DateTime(1969, 12, 31, 18, 0, 0)).Ticks;
file.LastWriteTime = new System.DateTime( (date * 10000L) + valueConstant );
return true;
}
catch (System.Exception exception)
{
String exceptionMessage = exception.Message;
return false;
}
}
}
}

81.GB2312文件转Unicode格式
/*
using System.IO;
using System.Text;
*/
File.WriteAllText(%%2, File.ReadAllText(%%1,Encoding.GetEncoding("GB2312")), Encoding.Unicode);

82.Java程序打包
/*
using System.IO;
using System.Collections;
using System.Diagnostics;
*/
string path = %%1;
path = (path.LastIndexOf(Path.DirectorySeparatorChar) == path.Length - 1) ? path : path + Path.DirectorySeparatorChar;
FileInfo myFilePath = new FileInfo(path + "conf.txt");
DirectoryInfo dir = new DirectoryInfo(path);
FileSystemInfo[] fileArr = dir.GetFileSystemInfos();
Queue<FileSystemInfo> Folders = new Queue<FileSystemInfo>(dir.GetFileSystemInfos());
while (Folders.Count > 0)
{
FileSystemInfo tmp = Folders.Dequeue();
FileInfo f = tmp as FileInfo;
if (f == null)
{
DirectoryInfo d = tmp as DirectoryInfo;
foreach (FileSystemInfo fi in d.GetFileSystemInfos())
{
Folders.Enqueue(fi);
}
}
else
{
if (f.Name.Substring(2).Contains('.')
&& f.Name.Substring(
f.Name.LastIndexOf('.'))
== ".java")
{
className = f.Name.Substring(0,
f.Name.LastIndexOf('.'));
Stream resultFile = myFilePath.Open(FileMode.OpenOrCreate);
StreamWriter myFile = new StreamWriter(resultFile);
myFile.WriteLine("Main-Class:" + className);
myFile.Flush();
myFile.Close();
resultFile.Close();
LandFileDivisison = new System.Diagnostics.Process();
LandFileDivisison.StartInfo.FileName = "javac "
+ f.FullName
+ " && jar cmf "
+ myFilePath.FullName + " "
+ className + ".jar " + className
+ ".class";
LandFileDivisison.Start();
LandFileDivisison = new System.Diagnostics.Process();
LandFileDivisison.StartInfo.FileName = "java -jar " + className;
LandFileDivisison.Start();
}
}
}
dir = new DirectoryInfo(path);
fileArr = dir.GetFileSystemInfos();
Folders = new Queue<FileSystemInfo>(dir.GetFileSystemInfos());
while (Folders.Count > 0)
{
FileSystemInfo tmp = Folders.Dequeue();
FileInfo f = tmp as FileInfo;
if (f == null)
{
DirectoryInfo d = tmp as DirectoryInfo;
foreach (FileSystemInfo fi in d.GetFileSystemInfos())
{
Folders.Enqueue(fi);
}
}
else
{
if (f.Name.Substring(2).Contains('.')
&& f.Name.Substring(
f.Name.LastIndexOf('.'))
== ".class")
f.Delete();
}
}

83.UTF-8文件转Unicode格式

84.创建PDF文档

85.创建Word文档
/*
添加引用->COM->Microsoft Word 11.0 Object Library
using Word;
*/
//下面的例子中包括C#对Word文档的创建、插入表格、设置样式等操作:

//(例子中代码有些涉及数据信息部分被省略,重要是介绍一些C#操作word文档的方法)

public string CreateWordFile(string CheckedInfo)
{
string message = "";
try
{
Object Nothing = System.Reflection.Missing.Value;
Directory.CreateDirectory("C:/CNSI"); //创建文件所在目录

string name = "CNSI_" + DateTime.Now.ToShortString()+".doc";
object filename = "C://CNSI//" + name; //文件保存路径
//创建Word文档
Word.Application WordApp = new Word.ApplicationClass();
Word.Document WordDoc = WordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);

//添加页眉
WordApp.ActiveWindow.View.Type = WdViewType.wdOutlineView;

WordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekPrimaryHeader;
WordApp.ActiveWindow.ActivePane.Selection.InsertAfter("[页眉内容]");
WordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight;//设置右对齐
WordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekMainDocument;//跳出页眉设置

WordApp.Selection.ParagraphFormat.LineSpacing = 15f;//设置文档的行间距

//移动焦点并换行
object count = 14;

object WdLine = Word.WdUnits.wdLine;//换一行;
WordApp.Selection.MoveDown(ref WdLine, ref count, ref Nothing);//移动焦点
WordApp.Selection.TypeParagraph();//插入段落

//文档中创建表格
Word.Table newTable = WordDoc.Tables.Add(WordApp.Selection.Range, 12, 3, ref Nothing, ref Nothing);
//设置表格样式
newTable.Borders.OutsideLineStyle = Word.WdLineStyle.wdLineStyleThickThinLargeGap;
newTable.Borders.InsideLineStyle = Word.WdLineStyle.wdLineStyleSingle;
newTable.Columns[1].Width = 100f;
newTable.Columns[2].Width = 220f;
newTable.Columns[3].Width = 105f;

//填充表格内容
newTable.Cell(1, 1).Range.Text = "产品详细信息表";
newTable.Cell(1, 1).Range.Bold = 2;//设置单元格中字体为粗体 软件开发网 www.mscto.com
//合并单元格
newTable.Cell(1, 1).Merge(newTable.Cell(1, 3));
WordApp.Selection.Cells.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;//垂直居中
WordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;//水平居中

//填充表格内容
newTable.Cell(2, 1).Range.Text = "产品基本信息";
newTable.Cell(2, 1).Range.Font.Color = Word.WdColor.wdColorDarkBlue;//设置单元格内字体颜色
//合并单元格
newTable.Cell(2, 1).Merge(newTable.Cell(2, 3));
WordApp.Selection.Cells.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;

//填充表格内容
newTable.Cell(3, 1).Range.Text = "品牌名称:";
newTable.Cell(3, 2).Range.Text = BrandName;

//纵向合并单元格
newTable.Cell(3, 3).Select();//选中一行
object moveUnit = Word.WdUnits.wdLine;
object moveCount = 5;
object moveExtend = Word.WdMovementType.wdExtend;
WordApp.Selection.MoveDown(ref moveUnit, ref moveCount, ref moveExtend);
WordApp.Selection.Cells.Merge();
//插入图片
string FileName = Picture;//图片所在路径
object LinkToFile = false;
object SaveWithDocument = true;
object Anchor = WordDoc.Application.Selection.Range;
WordDoc.Application.ActiveDocument.InlineShapes.AddPicture(FileName, ref LinkToFile, ref SaveWithDocument, ref Anchor);
WordDoc.Application.ActiveDocument.InlineShapes[1].Width = 100f;//图片宽度

WordDoc.Application.ActiveDocument.InlineShapes[1].Height = 100f;//图片高度
//将图片设置为四周环绕型
Word.Shape s = WordDoc.Application.ActiveDocument.InlineShapes[1].ConvertToShape();
s.WrapFormat.Type = Word.WdWrapType.wdWrapSquare;

newTable.Cell(12, 1).Range.Text = "产品特殊属性";
newTable.Cell(12, 1).Merge(newTable.Cell(12, 3));
//在表格中增加行
WordDoc.Content.Tables[1].Rows.Add(ref Nothing);

WordDoc.Paragraphs.Last.Range.Text = "文档创建时间:" + DateTime.Now.ToString();//“落款”
WordDoc.Paragraphs.Last.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight;


//文件保存
WordDoc.SaveAs(ref filename, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing);
WordDoc.Close(ref Nothing, ref Nothing, ref Nothing);
WordApp.Quit(ref Nothing, ref Nothing, ref Nothing);
message=name+"文档生成成功,以保存到C:CNSI下";
}
catch
{
message = "文件导出异常!";
}
return message;
}

86.快速高效的文件加密
/*
using System.IO;
using System.Windows.Forms.Design;//加载System.Design.dll的.Net API
*/
private static int ka,kb,kc,kd;
int[] a={2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2};
int[] b={3,3,3,5,5,3,3,3,5,3,5,3,7,3,11,7,11,3,5,3,3,3,7,5,5,3,7,3,11,13,3};
int[] c={3,5,7,5,7,11,13,19,17,29,19,31,17,41,11,19,13,47,29,53,59,67,29,41,43,71,31,73,23,23,101};
int[] d={5,7,11,13,17,17,19,29,43,43,47,47,59,61,61,67,71,71,73,79,89,101,101,103,107,107,109,109,127,149,151};

private static int niyuan(int m,int n)
{
int a,b,c,d,t,yu,shang,mod;
a=m;
b=n;
mod=a;
c=0;
d=1;
while(b<0)
b+=a;
if(a%b==0 || b%2==0)
return 0;
while(b!=1)
{
t=a%b;
shang=a/b;
a=b;
b=t;
yu=c-shang*d;
c=d;
d=yu;
}
if(yu<0)
yu+=mod;
return yu;
}

private static int GetDaysInMoths(int nMonths)
{
return new DateTime(DateTime.Now.Year,nMonths).DaysInMonth;
}

private static void init()
{
DateTime t2=new DateTime(1979,9,23);
DateTime t1=DateTime.Now;
TimeSpan ts=t1-t2;
Random rand=new Random(ts.Days*8-55);
UInt32 r=rand.NextDouble()*(GetDaysInMonths(t2.Month)));
ka=a[r];
kb=b[r];
kc=c[r];
kd=d[r];
}

private class FolderDialog : FolderNameEditor
{
FolderNameEditor.FolderBrowser fDialog = new
System.Windows.Forms.Design.FolderNameEditor.FolderBrowser();
public FolderDialog()
{
}
public DialogResult DisplayDialog()
{
return DisplayDialog("请选择一个文件夹");
}

public DialogResult DisplayDialog(string description)
{
fDialog.Description = description;
return fDialog.ShowDialog();
}
public string Path
{
get
{
return fDialog.DirectoryPath;
}
}
~FolderDialog()
{
fDialog.Dispose();
}
}

FolderDialog dlg = new FolderDialog();
dlg.DisplayDialog();
FolderDialog dlg2 = new FolderDialog();
dlg.DisplayDialog();
if(dlg.ShowDialog()==DialogResult.OK)
{
if(Path.GetExtension(dlg.SelectedPath).ToLower()==".txt")
{
if(dlg2.ShowDialog()==DialogResult.OK )
{
init();
}
}
else
{
if(dlg2.ShowDialog()==DialogResult.OK )
{
init();
}
}

87.从CSV文件构造XML文档
/*
using System.IO;
using System.Xml.Linq;
using System.Net;
using System.Text.RegularExpressions;
*/
string[] quotes=File.ReadLines(%%1);
XElement stockQuotes=new XElement("Root",from quote in quotes
let fields=quote.Split(new char[]{',','-'},StringSplitOption.RemoveEmptyEntries)
select new XElement("Company",fields[0].Trim()),
new XElement("LastPrice",fields[2].Trim()),
new XElement("Time",fields[1].Trim()),
new XElement("HighToday",fields[3].Trim()),
stockQuotes.Save(%%2);

88.从XML文档生成CSV文件
/*
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
*/
XElement black=XElement.Load(%%1);
string file=
(from elem in black.Elements("Player")
let statistics=elem.Element("Statistics")
select string.Format("{0},{1},{2},{3}",
(string)statistics.Attribute("Name"),
(string)statistics.Element("AverageAmountLost"),
(string)statistics.Element("AverageAmountWon"),
Environment.NewLine)),
Aggregate(new StringBuilder(),(builder,str)=>builder.Append(str),
builder=>builder.ToString());
FileInfo f = new FileInfo(%%2);
StreamWriter w = f.CreateText();
w.Write(file);
w.Flush();
w.Close();

89.模拟键盘输入字符串
//using System.Windows.Forms;
SendKeys.SendWait(%%1);

90.提取PDF文件中的文本
xpdf
public OpenFileDialog ofdlg = new OpenFileDialog();//打开文件对话框
public string filename;

public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
ofdlg.Filter = "pdf文件(*.pdf)|*.pdf";//选择pdf文件
if (ofdlg.ShowDialog() == DialogResult.OK)
{
filename = string.Format("{0}", ofdlg.FileName);
}
}
//传送打开文件对话框中得到的filename来做为外部程序的参数来做转化
private void button2_Click(object sender, EventArgs e)
{
Process p = new Process();
string path = "pdftotext.exe"; //进程启用外部程序
//这个exe我放在debug文件夹下面
p.StartInfo.FileName = path;
p.StartInfo.Arguments = string.Format( filename + " -");//很怪异的一行
//参数“-”表示可以得到输出流
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.CreateNoWindow = true;

p.Start();
string s = p.StandardOutput.ReadToEnd();//得到pdf文档中的文本内容
textBox1.Text = s;
p.Close();
}
}

上面的程序运行后,如果是在Debug文件夹下的pdf文件就可以得到输出,可是如果在打开文件对话框中打开我桌面上的一个pdf如:@"d:\我的文档\test.pdf",输出就会是空,但是如果把上面那怪异的一行改为:
C# code
p.StartInfo.Arguments = string.Format( @"d:\我的文档\test.pdf" + " -");


程序就又会得到输出。
呵呵,谢谢楼上的兄台,下载的xpdf中xpdftotext.exe用到的配置文件xpdfrc需要手动配置,我如果把那些字体啊,什么的映射成绝对路径下的文件,就不会出现上面的问题,但是我把配置文件中的路径改成了相对路径,于是就出现了上面的问题了,看兄台能够很轻易的就运行成功,一定是做过很多代码的,这里还得劳烦兄台再给看一下,帮下忙,能遇到一个大神不容易,大神可不能吝啬啊,先谢过了哈

91.操作内存映射文件
/*
using System.Runtime.InteropServices;
[DllImport("kernel32.dll")]
public static extern IntPtr CreateFileMapping(IntPtr hFile,
IntPtr lpFileMappingAttributes, uint flProtect,
uint dwMaximumSizeHigh,
uint dwMaximumSizeLow, string lpName);

[DllImport("kernel32.dll")]
public static extern IntPtr MapViewOfFile(IntPtr hFileMappingObject, uint
dwDesiredAccess, uint dwFileOffsetHigh, uint dwFileOffsetLow,
IntPtr dwNumberOfBytesToMap);

[DllImport("kernel32.dll")]
public static extern bool UnmapViewOfFile(IntPtr lpBaseAddress);

[DllImport("kernel32.dll")]
public static extern bool CloseHandle(IntPtr hObject);

[DllImport("kernel32.dll")]
public static extern IntPtr CreateFile(string lpFileName,
int dwDesiredAccess, FileShare dwShareMode, IntPtr securityAttrs,
FileMode dwCreationDisposition, int dwFlagsAndAttributes, IntPtr hTemplateFile);

[DllImport("kernel32.dll")]
public static extern uint GetFileSize(IntPtr hFile, IntPtr lpFileSizeHigh);

public const int GENERIC_READ = -2147483648; //0x80000000
public const int GENERIC_WRITE = 0x40000000;
public const int GENERIC_EXECUTE = 0x20000000;
public const int GENERIC_ALL = 0x10000000;
public const int FILE_ATTRIBUTE_NORMAL = 0x80;
public const int FILE_FLAG_SEQUENTIAL_SCAN = 0x8000000;
public const int INVALID_HANDLE_VALUE = -1;

public const int PAGE_NOACCESS = 1;
public const int PAGE_READONLY = 2;
public const int PAGE_READWRITE = 4;

public const int FILE_MAP_COPY = 1;
public const int FILE_MAP_WRITE = 2;
public const int FILE_MAP_READ = 4;
*/
IntPtr vFileHandle = CreateFile(@"c:\temp\temp.txt",
GENERIC_READ | GENERIC_WRITE, FileShare.Read | FileShare.Write,
IntPtr.Zero, FileMode.Open,
FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, IntPtr.Zero);
if (INVALID_HANDLE_VALUE != (int)vFileHandle)
{
IntPtr vMappingHandle = CreateFileMapping(
vFileHandle, IntPtr.Zero, PAGE_READWRITE, 0, 0, "~MappingTemp");
if (vMappingHandle != IntPtr.Zero)
{
IntPtr vHead = MapViewOfFile(vMappingHandle,
FILE_MAP_COPY | FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, IntPtr.Zero);
if (vHead != IntPtr.Zero)
{
uint vSize = GetFileSize(vFileHandle, IntPtr.Zero);
for (int i = 0; i <= vSize / 2; i++)
{
byte vTemp = Marshal.ReadByte((IntPtr)((int)vHead + i));
Marshal.WriteByte((IntPtr)((int)vHead + i),
Marshal.ReadByte((IntPtr)((int)vHead + vSize - i - 1)));
Marshal.WriteByte((IntPtr)((int)vHead + vSize - i - 1), vTemp);
}
UnmapViewOfFile(vHead);
}
CloseHandle(vMappingHandle);
}
CloseHandle(vFileHandle);
}

92.重定向windows控制台程序的输出信息
//using System.Diagnostics;
delegate void dReadLine(string strLine);
private void excuteCommand(string strFile, string args, dReadLine onReadLine)
{
System.Diagnostics.Process p = new Process();
p.StartInfo = new System.Diagnostics.ProcessStartInfo();
p.StartInfo.FileName = strFile;
p.StartInfo.Arguments = args;
p.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.UseShellExecute = false;
p.StartInfo.CreateNoWindow = true;
p.Start();
System.IO.StreamReader reader = p.StandardOutput;//截取输出流
string line = reader.ReadLine();//每次读取一行
while (!reader.EndOfStream)
{
onReadLine(line);
line = reader.ReadLine();
}
p.WaitForExit();
}
private void PrintMessage(string strLine)
{
%%2 += strLine + " ";
}
excuteCommand("cmd", " "+%%1, new dReadLine(PrintMessage));

//先读取文本中的命令假设为strCommand
string strCommand="ipconfig";
string strRst=string.Empty;
Process p = new Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.Arguments = "/c " + strCommand;

p.StartInfo.UseShellExecute = false;
//重定向标准输入
//p.StartInfo.RedirectStandardInput = false;
//重定向标准输出
p.StartInfo.RedirectStandardOutput = true;
//重定向错误输出
p.StartInfo.RedirectStandardError = false;
//设置不显示窗口
p.StartInfo.CreateNoWindow = true;
try
{
//启动进程
p.Start();
//停止3秒钟
Thread.Sleep(3000);
//如果进程结束
//或者你可以等到结束再获取
if (p.HasExited)
{

//从输出流获取执行结果
strRst = p.StandardOutput.ReadToEnd();
}
else
{
p.Kill();
}
}
catch (Exception ex)
{
strRst = "";
}
finally
{
p.Close();
}
//strRst即为运行后的结果,再将他写入另一个文本

93.序列化
using System.Collections;
using System.Text;

namespace SerializableTest
{
[Serializable]
public class Book
{
public Book()
{
alBookReader = new ArrayList();
}

public string strBookName;

[NonSerialized]
public string strBookPwd;

private string _bookID;
public string BookID
{
get { return _bookID; }
set { _bookID = value; }
}

public ArrayList alBookReader;

private string _bookPrice;
public void SetBookPrice(string price)
{
_bookPrice = price;
}

public void Write()
{
Console.WriteLine("Book ID:" + BookID);
Console.WriteLine("Book Name:" + strBookName);
Console.WriteLine("Book Password:" + strBookPwd);
Console.WriteLine("Book Price:" + _bookPrice);
Console.WriteLine("Book Reader:");
for (int i = 0; i < alBookReader.Count; i++)
{
Console.WriteLine(alBookReader[i]);
}
}
}
}
using (FileStream fs = new FileStream(strFile, FileMode.Create))
{
Book book = new Book();
book.BookID = "1";
book.alBookReader.Add("gspring");
book.alBookReader.Add("永春");
book.strBookName = "C#强化";
book.strBookPwd = "*****";
book.SetBookPrice("50.00");
BinarySerialize serialize = new BinarySerialize();
serialize.Serialize(book);
}

94.反序列化
using System.Collections;
using System.Text;

namespace SerializableTest
{
[Serializable]
public class Book
{
public Book()
{
alBookReader = new ArrayList();
}

public string strBookName;

[NonSerialized]
public string strBookPwd;

private string _bookID;
public string BookID
{
get { return _bookID; }
set { _bookID = value; }
}

public ArrayList alBookReader;

private string _bookPrice;
public void SetBookPrice(string price)
{
_bookPrice = price;
}

public void Write()
{
Console.WriteLine("Book ID:" + BookID);
Console.WriteLine("Book Name:" + strBookName);
Console.WriteLine("Book Password:" + strBookPwd);
Console.WriteLine("Book Price:" + _bookPrice);
Console.WriteLine("Book Reader:");
for (int i = 0; i < alBookReader.Count; i++)
{
Console.WriteLine(alBookReader[i]);
}
}
}
}
Book book;
using (FileStream fs = new FileStream(strFile, FileMode.Open))
{
BinaryFormatter formatter = new BinaryFormatter();
book = (Book)formatter.Deserialize(fs);
}
return book;

95.报表相关
/*
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;
*/
2、水晶报表的两种格式
1)pull模式,不利用DataSet,直接从数据库中取出数据
2) push模式,使用DataSet,利用它进行数据的加载和处理等
3. 水晶报表使用的库
1)水晶报表的引擎(CREnging.dll),作用:合并数据,装换格式
2)水晶报表设计器(CRDesigner.dll),作用:设计标题,插入数据等
3)水晶报表查看控件(CRWebFormViewer.DLL)
4)需要引入的命名空间
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;
4、Pull模式下使用水晶报表
1)创建rpt文件
2)拖放CrystalReportViewer
3)绑定
5、读取水晶报表文件
private void ReadCRV(cryatalReportViewer crv)
{
openFileDialog dlg=new OpenFileDialog();
dlg.Title="打开水晶报表文件";
dlg.Filter="水晶报表文件(*.rpt)|*.rpt|所有文件|*.*";
if(dlg.showDialog()==DialogResult.OK)
{
crv.ReportSource=dlg.FileName;
}
}
6. B/S下读取报表的文件
private void ReadCRV(cryatalReportViewer crv,File file)
{
string strName=file.PostedFile.FileName;
if(strName.Trim()!="")
{
crv.ReportSource=strName
Session["fileName"]=strName;
}
}
在B/S中要防止数据源的丢失
priavte void Page_Load(object sender,System.EventArgs e)
{
if(Session["fileName"]!=null)
{
crv.ReportSource=Session["fileName"].ToString();
}
}
7. 假如直接从数据库中读取数据,采用PULL模式可能出现错误(登录的用户名和密码不对)
private void ReadCRV(CrystalReportViewer crv,CrystalReport cr)
{
ReportDocument reportDoc=new ReportDocument();
reportDoc.Load(Server.MapPath(cr));//要加载的rpt文件的名字
//解决登录的问题
TableLogOnInfo logonInfo = new TableLogOnInfo();
foreach(Table tb in ReportDoc.Database.Tables)
{
logonInfo=tb.LogOnInfo;
logonInfo.ConnectionInfo.ServerName="(loacl)";
logonInfo.ConnectionInfo.DatabaseName="Pubs";
logonInfo.ConnectionInfo.UserId="sa";
logonInfo.ConnectionInfo.Password="";
tb.ApplyLogOnInfo(logonInfo);
}
crv.ReportSource=reportDoc;
}
8. 采用Push模式,直接在数据源读取
private void BindReport(CrystalReportViewer crv)
{
string strProvider="Server=(local);DataBase=pubs;uid=sa;pwd=";
CrystalReport cr=new CrystalReport();
DataSet ds=new DataSet();
SqlConnection conn=new SqlConnection(strProvider);
conn.open();
string strSql="select * from jobs";
SqlDataAdapter dap=new SqlDataAdapter(strSql,conn);
adp.Fill(ds,"jobs");
cr.SetDataSource(ds);
crv.ReportSource=cr;
}
9. 导出水晶报表的文件
private void ExportCrv(CrystalReport cr)
{
DiskFileDestionOptions dOpt=new DiskFileDestionOptions();
cr.ExportOptions.ExportDestinationType=ExportDestinationType.DiskFile();
cr.ExportOptions.ExportFormatType= ExportFormatType.PortableDocFormat;
dOpt.DiskFileName="C:\output.pdf";
cr.ExportOptions.DestinationOptions=dOpt;
cr.Export();

}
private void ExportCrv(CrystalReport cr,string strType,string strPath)
{
DiskFileDestionOptions dOpt=new DiskFileDestionOptions();
cr.ExportOptions.ExportDestinationType=ExportDestinationType.DiskFile();
switch(strType)
{
case "RTF":
cr.ExportOptions.ExportFormatType=ExportFormatType.RichText;
dOpt.DiskFileName=strPath;
break;
case "PDF":
cr.ExportOptions.ExportFormatType=ExportFormatType.PortableDocFormat;
dOpt.DiskFileName=strPath;
break;
case "DOC":
cr.ExportOptions.ExportFormatType=ExportFormatType.WordForWindows;
dOpt.DiskFileName=strPath;
break;
case "XLS":
cr.ExportOptions.ExportFormatType=ExportFormatType.Excel;
dOpt.DiskFileName=strPath;
break;
default;
break;

}
cr.ExportOptions.DestinationOptions=dOpt;
cr.Export();

}
10 B/S下水晶报表的打印
priavte void PrintCRV(CrystalReport cr)
{
string strPrinterName=@"printName";
PageMargins margins=cr.PrintOptions.PageMargins;
margins.bottomMargin = 250;
margins.leftMargin = 350;
margins.rightMargin = 350;
margins.topMargin = 450;
cr.PrintOptions.ApplyPageMargins(margins);
cr.PrintOptions.printerName=strPrinterName;
cr.PrintToPrinter(1,false,0,0)//参数设置为0,表示打印所用页
}

96.全屏幕截取

/*
using System.Drawing.Drawing2D;
using System.Runtime.InteropServices;
using System.Collections;
using System.Drawing.Imaging;
using System.Threading;
*/
[DllImport("gdi32.dll")]
private static extern int BitBlt(IntPtr hdcDest,int nXDest,int nYDest,int nWidth,int nHeight,IntPtr hdcSrc,int nXSrc,int nYSrc,UInt32 dwRop);
//this.Hide();//如果你不想截取的图象中有此应用程序
//Thread.Sleep(1000);
Rectangle rect = new Rectangle();
rect = Screen.GetWorkingArea(this);//获得当前屏幕的大小
Graphics g = this.CreateGraphics();
//创建一个以当前屏幕为模板的图象
Image myp_w_picpath = new Bitmap(rect.Width, rect.Height, g);
//第二种得到全屏坐标的方法
// Image myp_w_picpath = new Bitmap(Screen.PrimaryScreen.Bounds.Width,Screen.PrimaryScreen.Bounds.Height,g);
//创建以屏幕大小为标准的位图
Graphics gg = Graphics.FromImage(myp_w_picpath);
IntPtr dc = g.GetHdc();//得到屏幕的DC
IntPtr dcdc = gg.GetHdc();//得到Bitmap的DC
BitBlt(dcdc, 0, 0, rect.Width, rect.Height, dc, 0, 0, 13369376);
//调用此API函数,实现屏幕捕获
g.ReleaseHdc(dc);//释放掉屏幕的DC
gg.ReleaseHdc(dcdc);//释放掉Bitmap的DC
myp_w_picpath.Save(Application.StartupPath + @"\bob.jpg", ImageFormat.Jpeg);//以JPG文件格式来保存
this.Show();

97.区域截屏
/*
using System.Drawing.Drawing2D;
using System.Runtime.InteropServices;
using System.Collections;
using System.Drawing.Imaging;
using System.Threading;
[DllImport("gdi32.dll")]
public static extern IntPtr CreateDC(
string lpszDriver, // driver name
string lpszDevice, // device name
string lpszOutput, // not used; should be NULL
Int64 lpInitData // optional printer data
);

[DllImport("gdi32.dll")]
public static extern IntPtr CreateCompatibleDC(
IntPtr hdc // handle to DC
);

[DllImport("gdi32.dll")]
public static extern int GetDeviceCaps(
IntPtr hdc, // handle to DC
GetDeviceCapsIndex nIndex // index of capability
);

[DllImport("gdi32.dll")]
public static extern IntPtr CreateCompatibleBitmap(
IntPtr hdc, // handle to DC
int nWidth, // width of bitmap, in pixels
int nHeight // height of bitmap, in pixels
);

[DllImport("gdi32.dll")]
public static extern IntPtr SelectObject(
IntPtr hdc, // handle to DC
IntPtr hgdiobj // handle to object
);

[DllImport("gdi32.dll")]
public static extern int BitBlt(
IntPtr hdcDest, // handle to destination DC
int nXDest, // x-coord of destination upper-left corner
int nYDest, // y-coord of destination upper-left corner
int nWidth, // width of destination rectangle
int nHeight, // height of destination rectangle
IntPtr hdcSrc, // handle to source DC
int nXSrc, // x-coordinate of source upper-left corner
int nYSrc, // y-coordinate of source upper-left corner
UInt32 dwRop // raster operation code
);

[DllImport("gdi32.dll")]
public static extern int DeleteDC(
IntPtr hdc // handle to DC
);
*/
public static Bitmap GetPartScreen(Point P1,Point P2,bool Full)
{
IntPtr hscrdc,hmemdc;
IntPtr hbitmap,holdbitmap;
int nx,ny,nx2,ny2;
nx=ny=nx2=ny2=0;
int nwidth, nheight;
int xscrn, yscrn;
hscrdc = CreateDC("DISPLAY", null, null, 0);//创建DC句柄
hmemdc = CreateCompatibleDC(hscrdc);//创建一个内存DC
xscrn = GetDeviceCaps(hscrdc, GetDeviceCapsIndex.HORZRES);//获取屏幕宽度
yscrn = GetDeviceCaps(hscrdc, GetDeviceCapsIndex.VERTRES);//获取屏幕高度
if(Full)//如果是截取整个屏幕
{
nx = 0;
ny = 0;
nx2 = xscrn;
ny2 = yscrn;
}
else
{
nx = P1.X;
ny = P1.Y;
nx2 =P2.X;
ny2 =P2.Y;
//检查数值合法性
if(nx<0)nx = 0;
if(ny<0)ny = 0;
if(nx2>xscrn)nx2 = xscrn;
if(ny2>yscrn)ny2 = yscrn;
}
nwidth = nx2 - nx;//截取范围的宽度
nheight = ny2 - ny;//截取范围的高度
hbitmap = CreateCompatibleBitmap(hscrdc, nwidth, nheight);//从内存DC复制到hbitmap句柄
holdbitmap = SelectObject(hmemdc, hbitmap);
BitBlt(hmemdc, 0, 0, nwidth, nheight,hscrdc, nx, ny,(UInt32)0xcc0020);
hbitmap = SelectObject(hmemdc, holdbitmap);
DeleteDC(hscrdc);//删除用过的对象
DeleteDC(hmemdc);//删除用过的对象
return Bitmap.FromHbitmap(hbitmap);//用Bitmap.FromHbitmap从hbitmap返回Bitmap
}

98.计算文件MD5值
/*
using System.IO;
using System.Security.Cryptography;
*/
string path = %%1;
FileStream fs = new FileStream(path,FileMode.Open,FileAccess.Read);
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
byte [] md5byte = md5.ComputeHash(fs);
int i,j;
StringBuilder sb = new StringBuilder(16);
foreach (byte b in md5byte)
{
i = Convert.ToInt32(b);
j = i >> 4;
sb.Append(Convert.ToString(j,16));
j = ((i << 4) & 0x00ff) >> 4;
sb.Append(Convert.ToString(j,16));
}
string %%2=sb.ToString();

99.计算获取文件夹中文件的MD5值
/*
using System.IO;
using System.Security.Cryptography;
using System.Collections;
*/
bool b=false;
string path = (%%2.LastIndexOf(Path.DirectorySeparatorChar) == %%2.Length - 1) ? %%2 : %%2 + Path.DirectorySeparatorChar;
string parent = Path.GetDirectoryName(%%1);
Directory.CreateDirectory(path + Path.GetFileName(%%1));
DirectoryInfo dir = new DirectoryInfo((%%1.LastIndexOf(Path.DirectorySeparatorChar) == %%1.Length - 1) ? %%1 : %%1 + Path.DirectorySeparatorChar);
FileSystemInfo[] fileArr = dir.GetFileSystemInfos();
Queue<FileSystemInfo> Folders = new Queue<FileSystemInfo>(dir.GetFileSystemInfos());
while (Folders.Count > 0)
{
FileSystemInfo tmp = Folders.Dequeue();
FileInfo f = tmp as FileInfo;
if (b && f == null)
{
DirectoryInfo d = tmp as DirectoryInfo;
Directory.CreateDirectory(d.FullName.Replace((parent.LastIndexOf(Path.DirectorySeparatorChar) == parent.Length - 1) ? parent : parent + Path.DirectorySeparatorChar, path));
foreach (FileSystemInfo fi in d.GetFileSystemInfos())
{
Folders.Enqueue(fi);
}
}
else
{
FileStream fs = new FileStream(f,FileMode.Open,FileAccess.Read);
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
byte [] md5byte = md5.ComputeHash(fs);
int i,j;
StringBuilder sb = new StringBuilder(16);
foreach (byte b in md5byte)
{
i = Convert.ToInt32(b);
j = i >> 4;
sb.Append(Convert.ToString(j,16));
j = ((i << 4) & 0x00ff) >> 4;
sb.Append(Convert.ToString(j,16));
}
string %%3=sb.ToString();
}
}

100.复制一个目录下所有文件到一个文件夹中
/*
using System.IO;
using System.Collections;
*/
string path = (%%2.LastIndexOf(Path.DirectorySeparatorChar) == %%2.Length - 1) ? %%2 : %%2+Path.DirectorySeparatorChar;
string parent = Path.GetDirectoryName(%%1);
Directory.CreateDirectory(path + Path.GetFileName(%%1));
DirectoryInfo dir = new DirectoryInfo((%%1.LastIndexOf(Path.DirectorySeparatorChar) == %%1.Length - 1) ? %%1 : %%1 + Path.DirectorySeparatorChar);
FileSystemInfo[] fileArr = dir.GetFileSystemInfos();
Queue<FileSystemInfo> Folders = new Queue<FileSystemInfo>(dir.GetFileSystemInfos());
while (Folders.Count>0)
{
FileSystemInfo tmp = Folders.Dequeue();
FileInfo f = tmp as FileInfo;
if (f == null)
{
DirectoryInfo d = tmp as DirectoryInfo;
foreach (FileSystemInfo fi in d.GetFileSystemInfos())
{
Folders.Enqueue(fi);
}
}
else
{
f.CopyTo(path+f.Name);
}
}

101.移动一个目录下所有文件到一个文件夹中
/*
using System.IO;
using System.Collections;
*/
string path = (%%2.LastIndexOf(Path.DirectorySeparatorChar) == %%2.Length - 1) ? %%2 : %%2+Path.DirectorySeparatorChar;
string parent = Path.GetDirectoryName(%%1);
Directory.CreateDirectory(path + Path.GetFileName(%%1));
DirectoryInfo dir = new DirectoryInfo((%%1.LastIndexOf(Path.DirectorySeparatorChar) == %%1.Length - 1) ? %%1 : %%1 + Path.DirectorySeparatorChar);
FileSystemInfo[] fileArr = dir.GetFileSystemInfos();
Queue<FileSystemInfo> Folders = new Queue<FileSystemInfo>(dir.GetFileSystemInfos());
while (Folders.Count>0)
{
FileSystemInfo tmp = Folders.Dequeue();
FileInfo f = tmp as FileInfo;
if (f == null)
{
DirectoryInfo d = tmp as DirectoryInfo;
foreach (FileSystemInfo fi in d.GetFileSystemInfos())
{
Folders.Enqueue(fi);
}
}
else
{
f.MoveTo(path+f.Name);
}
}

102.文件RSA高级加密
/*
using System.IO;
using System.Security.Cryptography;
private RSACryptoServiceProvider _rsa;
*/
FileStream fin=new FileStream(%%1,FileMode.Open,FileAccess.Read);
FileStream fout=new FileStream(%%2,FileMode.OpenOrCreate,FileAccess.Write);
byte[] readBuffer=new byte[128];
fin.Read(readBuffer,0,readBuffer.Length);
byte[] encryptedBuffer=_rsa.Encrypt(readBuffer,true);
_rsa.Clear();

103.计算文件大小
/*
using System.IO;
private const long KB=1024;
private const long MB=1024*KB;
private const long GB=1024*MB;
*/
FileInfo fi = new FileInfo(%%1);
long filesize= fi.Length;
string showsize;
if(filesize>=GB)
showsize.format("%0.2f GB",(double)filesize/GB);
else if(filesize>=MB)
showsize.format("%0.2f MB",(double)filesize/MB);
else if(filesize>=KB)
showsize.format("%0.2f KB",(double)filesize/KB);
else if(filesize>1)
showsize.format("%ld Bytes",filesize);
else
showsize="1 Byte";
string %%2=showsize;

104.计算文件夹的大小
/*
using System.IO;
private const long KB=1024;
private const long MB=1024*KB;
private const long GB=1024*MB;
*/
private static long FolderFileSize(string path)
{
long size = 0;
try
{
FileInfo [] files = (new DirectoryInfo(path)).GetFiles();
foreach(FileInfo file in files)
{
size += file.Length;
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
return size;
}

private static long FolderSize(string path)
{
long Fsize = 0;
try
{
Fsize = FolderFileSize(path);
DirectoryInfo [] folders = (new DirectoryInfo(path)).GetDirectories();
foreach(DirectoryInfo folder in folders)
Fsize += FolderSize(folder.FullName);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
return Fsize;
}
long filesize= FolderSize(%%1);
string showsize;
if(filesize>=GB)
showsize.format("%0.2f GB",(double)filesize/GB);
else if(filesize>=MB)
showsize.format("%0.2f MB",(double)filesize/MB);
else if(filesize>=KB)
showsize.format("%0.2f KB",(double)filesize/KB);
else if(filesize>1)
showsize.format("%ld Bytes",filesize);
else
showsize="1 Byte";
string %%2=showsize;

105.快速获得当前程序的驱动器、路径、文件名和扩展名
//using System.IO;
DirectoryInfo dires= new DirectoryInfo(Application.StartupPath);
string strQDQ = null;//驱动器
strQDQ = dires.Root.ToString();
string strPath =Application.ExecutablePath;//路径

string FName = null;//文件名
string FNameExt = null;//扩展名
FileInfo FileIno = new FileInfo(strPath);
FName = FileIno.Name;
FNameExt = FileIno.Extension;

106.磁盘剩余空间计算
/*
using System.Runtime.InteropServices;
//第一种
[DllImport("kernel32")]
public static extern bool GetDiskFreeSpaceEx(string Path,out long
bytesAvail, out long bytesOnDisk, out long freeBytesOnDisk);

long bytesAvail, bytesOnDisk,freeBytesOnDisk,lpTotalNumberOfClusters;
//lpRootPathName String,不包括卷名的一个磁盘根路径
//lpSectorsPerCluster Long,用于装载一个簇内扇区数的变量
//lpBytesPerSector Long,用于装载一个扇区内字节数的变量
//lpNumberOfFreeClusters Long,用于装载磁盘上剩余簇数的变量
//lpTtoalNumberOfClusters Long,用于装载磁盘上总簇数的变量
*/
string tempImagePath = Application.StartupPath;//取出应用安装的目录。
GetDiskFreeSpaceEx(tempImagePath, out bytesAvail, out bytesOnDisk, out freeBytesOnDisk);
textBox1.Text = (freeBytesOnDisk/1024/1024).ToString();

//第二种 引用System.Management
//using System.Management;
ManagementClass diskClass = new ManagementClass("Win32_LogicalDisk");
ManagementObjectCollection disks=diskClass.GetInstances();
System.UInt64 space=UInt64.MinValue;
foreach(ManagementObject disk in disks)
{
if((disk["Name"]).ToString() == "C:")
space = (System.UInt64)(disk["FreeSpace"]);
}
//第三种 framework 中已经有类了, 不需要调用 API
//using System.IO;
long x = new DriveInfo(%%1).AvailableFreeSpace; //"C"
string showsize;
if (x >= GB)
showsize.format("%0.2f GB", (double)x / GB);
else if (x >= MB)
showsize.format("%0.2f MB", (double)x / MB);
else if (x >= KB)
showsize.format("%0.2f KB", (double)x / KB);
else if (x > 1)
showsize.format("%ld Bytes", x);
else
showsize = "1 Byte";
return showsize;

107.获取当前程序进程ID
//using System.Diagnostics;
int %%1 = Process.GetCurrentProcess().Id;

108.全盘搜索文件
/*
using System.Text;
using System.IO;
*/
string strFileName;
public string StrFileName{get { return strFileName; }set { strFileName = value; }}
delegate void Temp(string fileName);
delegate void ShowProgressDelegate(string fileName, string filePath, IList<IlsitFileFindModleClass> objIlist);
IList<IlsitFileFindModleClass> objIlist;
public void GetFoldersPath(){
if (GridSearch.InvokeRequired == false){}
else{
objIlist = new List<IlsitFileFindModleClass>();
string retStr = null;
DriveInfo[] allDrives = DriveInfo.GetDrives();//检索计算机上的所有逻辑驱动器的驱动器名称
foreach (DriveInfo driPath in allDrives){//循环输出各分区的信息
FileSeach(driPath.Name);
}
}
}
public void GetFoldersPath(string root){
if (GridSearch.InvokeRequired == false) { }
else { objIlist = new List<IlsitFileFindModleClass>(); FileSeach(root); }
}
public void FileSeach(string root){
string strFileNameTemp = StrFileName;
Stack<string> dirs = new Stack<string>(20);
if (!System.IO.Directory.Exists(root))
return;
dirs.Push(root);
while (dirs.Count > 0){
string currentDir = dirs.Pop();
string[] subDirs;
try{
subDirs = System.IO.Directory.GetDirectories(currentDir);
}
catch (UnauthorizedAccessException e) { continue; }
catch (System.IO.DirectoryNotFoundException e) { continue; }
Temp temp=new Temp(Testll);
label2.Invoke(temp, new object[] { currentDir });
try{
string[] filesTemp = System.IO.Directory.GetFiles(currentDir, StrFileName + ".*");
if (filesTemp.Length > 0){
objIlist.Add(new IlsitFileFindModleClass(strFileNameTemp, currentDir + "\\" + strFileNameTemp + ".*"));
ShowProgressDelegate objTemp = new ShowProgressDelegate(test);
BeginInvoke(objTemp, new object[] { strFileNameTemp, currentDir + "\\" + strFileNameTemp + ".*", objIlist });
continue;
}
}
catch (UnauthorizedAccessException e) { continue; }
catch (System.IO.DirectoryNotFoundException e) { continue; }
foreach (string str in subDirs)
dirs.Push(str);
}
}
StrFileName =%%1;
MethodInvoker mi = new MethodInvoker(GetFoldersPath);
mi.BeginInvoke(null, null);