程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> c#文件操作大全(二)

c#文件操作大全(二)

編輯:C#入門知識

61.文件夾移動到整合操作

            FolderDialog aa = new FolderDialog();
            aa.DisplayDialog();
            if (aa.Path != "")
            {
                string filename = Path.GetFileName(%%1);
                string path=(aa.Path.LastIndexOf("\") == aa.Path.Length - 1) ? aa.Path : aa.Path + "\";
                if (Path.GetPathRoot(%%1) == Path.GetPathRoot(aa.Path))
                    Directory.Move(%%1, path + filename);
                else
                {
                    string parent = Path.GetDirectoryName(%%1);
                    Directory.CreateDirectory(path + Path.GetFileName(%%1));
                    %%1 = (%%1.LastIndexOf("\") == %%1.Length - 1) ? %%1 : %%1 + "\";
                    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;
                            DirectoryInfo dpath = new DirectoryInfo(d.FullName.Replace((parent.LastIndexOf("\") == parent.Length - 1) ? parent : parent + "\", path));
                            dpath.Create();
                            foreach (FileSystemInfo fi in d.GetFileSystemInfos())
                            {
                                Folders.Enqueue(fi);
                            }
                        }
                        else
                        {
                            f.MoveTo(f.FullName.Replace(parent, path));
                        }
                    }
                    Directory.Delete(%%1, true);
                }
            }

62.目錄下所有文件夾復制到整合操作

            FolderDialog aa = new FolderDialog();
            aa.DisplayDialog();
            if (aa.Path != "")
            {
                string direc = %%1;//獲取選中的節點的完整路徑
                foreach (string dirStr in Directory.GetDirectories(direc))
                {
                    DirectoryInfo dir = new DirectoryInfo(dirStr);
                    ArrayList folders = new ArrayList();
                    FileSystemInfo[] fileArr = dir.GetFileSystemInfos();
                    folders.AddRange(fileArr);
                    for (int i = 0; i < folders.Count; i++)
                    {
                        FileInfo f = folders[i] as FileInfo;
                        if (f == null)
                        {
                            DirectoryInfo d = folders[i] as DirectoryInfo;
                            Directory.CreateDirectory(aa.Path + d.Name);
                            folders.AddRange(d.GetFileSystemInfos());
                        }
                        else
                            File.Copy(f.FullName, aa.Path + f.Name);
                    }
                }
            }

63.目錄下所有文件夾移動到整合操作

            FolderDialog aa = new FolderDialog();
            aa.DisplayDialog();
            if (aa.Path != "")
            {
                TreeNode CurSelNode = this.DirectorytreeView.SelectedNode;//獲取選中的節點
                string direc = this.GetNodeFullPath(CurSelNode);//獲取選中的節點的完整路徑
                if (Path.GetPathRoot(direc) == Path.GetPathRoot(aa.Path))
                    foreach (string dir in Directory.GetDirectories(direc))
                        Directory.Move(dir, aa.Path);
                else
                {
                    foreach (string dir2 in Directory.GetDirectories(direc))
                    {
                        string parent = Path.GetDirectoryName(dir2);
                        Directory.CreateDirectory(Path.Combine(aa.Path, Path.GetFileName(dir2)));
                        string dir = (dir2.LastIndexOf("\") == dir2.Length - 1) ? dir2 : dir2 + "\";
                        DirectoryInfo dirdir = new DirectoryInfo(dir);
                        FileSystemInfo[] fileArr = dirdir.GetFileSystemInfos();
                        Queue<FileSystemInfo> Folders = new Queue<FileSystemInfo>(dirdir.GetFileSystemInfos());
                        while (Folders.Count > 0)
                        {
                            FileSystemInfo tmp = Folders.Dequeue();
                            FileInfo f = tmp as FileInfo;
                            if (f == null)
                            {
                                DirectoryInfo d = tmp as DirectoryInfo;
                                DirectoryInfo dpath = new DirectoryInfo(d.FullName.Replace((parent.LastIndexOf("\") == parent.Length - 1) ? parent : parent + "\", aa.Path));
                                dpath.Create();
                                foreach (FileSystemInfo fi in d.GetFileSystemInfos())
                                {
                                    Folders.Enqueue(fi);
                                }
                            }
                            else
                            {
                                f.MoveTo(f.FullName.Replace(parent, aa.Path));
                            }
                        }
                        dirdir.Delete(true);
                    }
                }
            }

64.目錄下所有文件復制到整合操作

            FolderDialog aa = new FolderDialog();
            aa.DisplayDialog();
            if (aa.Path != "")
            {
                string direc = %%1;//獲取選中的節點的完整路徑
                foreach (string fileStr in Directory.GetFiles(direc))
                    File.Copy((direc.LastIndexOf("\") == direc.Length - 1) ? direc + Path.GetFileName(fileStr) : direc + "\" + Path.GetFileName(fileStr), (aa.Path.LastIndexOf("\") == aa.Path.Length - 1) ? aa.Path + Path.GetFileName(fileStr) : aa.Path + "\" + Path.GetFileName(fileStr));
            }

65.目錄下所有文件移動到整合操作

            FolderDialog aa = new FolderDialog();
            aa.DisplayDialog();
            if (aa.Path != "")
            {
                string direc = %%1;//獲取選中的節點的完整路徑
                foreach (string fileStr in Directory.GetFiles(direc))
                    File.Move((direc.LastIndexOf("\") == direc.Length - 1) ? direc + Path.GetFileName(fileStr) : direc + "\" + Path.GetFileName(fileStr), (aa.Path.LastIndexOf("\") == aa.Path.Length - 1) ? aa.Path + Path.GetFileName(fileStr) : aa.Path + "\" + Path.GetFileName(fileStr));
                DirectoryInfolistView.Clear();
            }

66.對目標壓縮文件解壓縮到指定文件夾

        private void DeSerializeFiles(Stream s, string dirPath)
        {
            BinaryFormatter b = new BinaryFormatter();
            ArrayList list = (ArrayList)b.Deserialize(s);
            foreach (SerializeFileInfo f in list)
            {
                string newName = dirPath + Path.GetFileName(f.FileName);
                using (FileStream fs = new FileStream(newName, FileMode.Create, FileAccess.Write))
                {
                    fs.Write(f.FileBuffer, 0, f.FileBuffer.Length);
                    fs.Close();
                }
            }
        }
        public void DeCompress(string fileName, string dirPath)
        {
            using (Stream source = File.OpenRead(fileName))
            {
                using (Stream destination = new MemoryStream())
                {
                    using (GZipStream input = new GZipStream(source, CompressionMode.Decompress, true))
                    {
                        byte[] bytes = new byte[4096];
                        int n;
                        while ((n = input.Read(bytes, 0, bytes.Length)) != 0)
                        {
destination.Write(bytes, 0, n);
                        }
                    }
                    destination.Flush();
                    destination.Position = 0;
                    DeSerializeFiles(destination, dirPath);
                }
            }
        }

67.創建目錄副本整合操作

            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("\") == aa.Path.Length - 1) ? aa.Path : aa.Path + "\";
                string parent = Path.GetDirectoryName(%%1);
                Directory.CreateDirectory(path + Path.GetFileName(%%1));
                %%1 = (%%1.LastIndexOf("\") == %%1.Length - 1) ? %%1 : %%1 + "\";
                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("\") == parent.Length - 1) ? parent : parent + "\", 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("IEXPLORE.EXE", "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.獲取磁盤所有分區後再把光驅盤符去除(用"\0"代替),把結果放在數組allfenqu[] 中,數組中每個元素代表一個分區盤符,不包括 :\\ 這樣的路徑,allfenqu[]數組開始時存放的是所有盤符。
當我用這樣的代碼測試結果是正確的,光驅盤符會被去掉:
//using System.IO;
stringroot; //root代表盤符路徑
for(i=0;i<20;i++) //0-20代表最大的盤符數
{
root.Format("%c:\",allfenqu[i]);
if(GetDriveType(root)==5)
allfenqu[i]='\0';
}

但我用這樣的代碼時結果卻無法去掉光驅盤符,allfenqu[]中還是會包含光驅盤符:
stringroot;
for(i=0;i<20;i++)
{
root=allfenqu[i]+":\";
if(GetDriveType(root)==5)
allfenqu[i]='\0';
}

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

72.HTTP下載

        private WebClient client = new WebClient();
            Thread th = new Thread(new ThreadStart(StartDownload));
            th.Start();
        private void StartDownload()
        {
            //Start.Enabled = false;
            string URL = %%1;
            int n = URL.LastIndexOf("/");
            string URLAddress = URL.Substring(0, n);
            string fileName = URL.Substring(n + 1, URL.Length - n - 1);
            string Dir = %%2;
            string Path = Dir.ToString() + "\" + fileName;
            try
            {
                WebRequest myre = WebRequest.Create(URLAddress);
            }
            catch (WebException exp)
            {
                MessageBox.Show(exp.Message, "Error");
            }
            try
            {
                //statusBar.Text = "開始下載文件...";
                client.DownloadFile(URLAddress, fileName);
                Stream str = client.OpenRead(URLAddress);
                StreamReader reader = new StreamReader(str);
                byte[] mbyte = new byte[100000];
                int allmybyte = (int)mbyte.Length;
                int startmbyte = 0;
                //statusBar.Text = "正在接收數據...";
                while (allmybyte > 0)
                {
                    int m = str.Read(mbyte, startmbyte, allmybyte);
                    if (m == 0)
                        break;
                    startmbyte += m;
                    allmybyte -= m;
                }
                FileStream fstr = new FileStream(Path, FileMode.OpenOrCreate, FileAccess.Write);
                fstr.Write(mbyte, 0, startmbyte);
                str.Close();
                fstr.Close();
                //statusBar.Text = "下載完畢!";
                MessageBox.Show("下載完畢");
            }
            catch (WebException exp)
            {
                MessageBox.Show(exp.Message, "Error");
                //statusBar.Text = "";
            }
            Start.Enabled = true;
        }

73.FTP下載

bool   IsValidFileChars(string   strIn) 
  { 
          Regex   regEx   =   new   Regex("[\\*\\\\/:?<>|"]");
          return   !regEx.IsMatch("aj\\pg"); 
  } 
public bool DownloadFile(string RemoteFileName, string LocalPath)
{
return DownloadFile(RemoteFileName, LocalPath, RemoteFileName);
}
/// <summary>
/// 從FTP服務器下載文件,指定本地路徑和本地文件名
/// </summary>
/// <param name="RemoteFileName">遠程文件名</param>
/// <param name="LocalPath">本地路徑</param>
/// <param name="LocalFilePath">保存文件的本地路徑,後面帶有""</param>
/// <param name="LocalFileName">保存本地的文件名</param>
public bool DownloadFile(string RemoteFileName, string LocalPath, string LocalFileName)
{
byte[] bt = null;
try
{
if (!IsValidFileChars(RemoteFileName) || !IsValidFileChars(LocalFileName) || !IsValidPathChars(LocalPath))
{
throw new Exception("非法文件名或目錄名!");
}
if (!Directory.Exists(LocalPath))
{
throw new Exception("本地文件路徑不存在!");
}

string LocalFullPath = Path.Combine(LocalPath, LocalFileName);
if (File.Exists(LocalFullPath))
{
throw new Exception("當前路徑下已經存在同名文件!");
}
bt = DownloadFile(RemoteFileName);
if (bt != null)
{
FileStream stream = new FileStream(LocalFullPath, FileMode.Create);
stream.Write(bt, 0, bt.Length);
stream.Flush();
stream.Close();
return true;
}
else
{
return false;
}
}
catch (Exception ep)
{
ErrorMsg = ep.ToString();
throw ep;
}
}

/// <summary>
/// 從FTP服務器下載文件,返回文件二進制數據
/// </summary>
/// <param name="RemoteFileName">遠程文件名</param>
public byte[] DownloadFile(string RemoteFileName)
{
try
{
if (!IsValidFileChars(RemoteFileName))
{
throw new Exception("非法文件名或目錄名!");
}
Response = Open(new Uri(this.Uri.ToString() + RemoteFileName), WebRequestMethods.Ftp.DownloadFile);
Stream Reader = Response.GetResponseStream();

MemoryStream mem = new MemoryStream(1024 * 500);
byte[] buffer = new byte[1024];
int bytesRead = 0;
int TotalByteRead = 0;
while (true)
{
bytesRead = Reader.Read(buffer, 0, buffer.Length);
TotalByteRead += bytesRead;
if (bytesRead == 0)
break;
mem.Write(buffer, 0, bytesRead);
}
if (mem.Length > 0)
{
return mem.ToArray();
}
else
{
return null;
}
}
catch (Exception ep)
{
ErrorMsg = ep.ToString();
throw ep;
}
}

74.寫圖像到剪切板 setClipboardImage
//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.拷貝文件名復制文件
//添加引用System.Windows.Forms
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Windows.Forms;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            IDataObject iData = Clipboard.GetDataObject();
            string str;
            // 將數據與指定的格式進行匹配,返回bool
            if (iData.GetDataPresent(DataFormats.Text))
            {
                // GetData檢索數據並指定一個格式
                str = (string)iData.GetData(DataFormats.Text);
                File.Copy(str, @"C:" + Path.GetFileName(str));
            }
            else
            {
                MessageBox.Show("目前剪貼板中數據不可轉換為文本", "錯誤");
            }
        }
    }
}

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 + "\" + files2.Name + "\";
            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 + "\" + 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("\") + 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 + "\" + 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("\") + 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 + "\" + 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.剪貼扳轉換成打印字符
//using System.Windows.Forms;
            IDataObject iData = Clipboard.GetDataObject();
            string str;
            // 將數據與指定的格式進行匹配,返回bool
            if (iData.GetDataPresent(DataFormats.Text))
            {
                // GetData檢索數據並指定一個格式
                str = (string)iData.GetData(DataFormats.Text);
                string[] arr = str.Split("\r\n".ToCharArray());
                StringBuilder sb = new StringBuilder(1024);
                sb.Append("System.out.println("@echooff");\r\n");
                foreach (string s in arr)
                {
                    if (s.Trim()!="")
                    {
                        sb.Append("System.out.println("ECHO " + s.Replace("^", "^^").Replace("&", "^&").Replace(":", "^:").Replace(">", "^>").Replace("<", "^<").Replace("|", "^|").Replace(""", "^"").Replace(@"", @"\").Replace("\"", "\\"") + "");");
                        sb.Append("\r\n");
                    }
                }
                Clipboard.SetText(sb.ToString());
            }
            else
            {
                MessageBox.Show("目前剪貼板中數據不可轉換為文本", "錯誤");
            }

82.把JButton或JTree組件寫到一個流中

83.注冊全局熱鍵
注冊全局熱鍵要用到Windows的API方法RegisterHotKey和UnregisterHotKey。
一、聲明注冊熱鍵方法 [DllImport("user32.dll")]
private static extern int RegisterHotKey(IntPtr hwnd, int id, int fsModifiers, int vk);
[DllImport("user32.dll")]
private static extern int UnregisterHotKey(IntPtr hwnd, int id);
int Space = 32; //熱鍵ID
private const int WM_HOTKEY = 0x312; //窗口消息-熱鍵
private const int WM_CREATE = 0x1; //窗口消息-創建
private const int WM_DESTROY = 0x2; //窗口消息-銷毀
private const int MOD_ALT = 0x1; //ALT
private const int MOD_CONTROL = 0x2; //CTRL
private const int MOD_SHIFT = 0x4; //SHIFT
private const int VK_SPACE = 0x20; //SPACE
二、注冊熱鍵方法 /// <summary>
/// 注冊熱鍵
/// </summary>
/// <param name="hwnd">窗口句柄</param>
/// <param name="hotKey_id">熱鍵ID</param>
/// <param name="fsModifiers">組合鍵</param>
/// <param name="vk">熱鍵</param>
private void RegKey(IntPtr hwnd, int hotKey_id, int fsModifiers, int vk)
{
bool result;
if (RegisterHotKey(hwnd,hotKey_id,fsModifiers,vk) == 0)
{
result = false;
}
else
{
result = true;
}
if (!result)
{
MessageBox.Show("注冊熱鍵失敗!");
}
}

/// <summary>
/// 注銷熱鍵
/// </summary>
/// <param name="hwnd">窗口句柄</param>
/// <param name="hotKey_id">熱鍵ID</param>
private void UnRegKey(IntPtr hwnd, int hotKey_id)
{
UnregisterHotKey(hwnd,hotKey_id);
}
三、重寫WndProc方法,實現注冊 protected override void WndProc(ref Message m)
{
base.WndProc(ref m);
switch(m.Msg)
{
case WM_HOTKEY: //窗口消息-熱鍵
switch(m.WParam.ToInt32())
{
case 32: //熱鍵ID
MessageBox.Show("Hot Key : Ctrl + Alt + Shift + Space");
break;
   default:
   break;
}
break;
case WM_CREATE: //窗口消息-創建
RegKey(Handle,Space,MOD_ALT | MOD_CONTROL | MOD_SHIFT,VK_SPACE); //注冊熱鍵
break;
case WM_DESTROY: //窗口消息-銷毀
UnRegKey(Handle,Space); //銷毀熱鍵
break;
default:
break;
}
}
附:虛擬鍵值表
{ Virtual Keys, Standard Set }
{$EXTERNALSYM VK_LBUTTON}
VK_LBUTTON = 1;
{$EXTERNALSYM VK_RBUTTON}
VK_RBUTTON = 2;
{$EXTERNALSYM VK_CANCEL}
VK_CANCEL = 3;
{$EXTERNALSYM VK_MBUTTON}
VK_MBUTTON = 4; { NOT contiguous with L & RBUTTON }
{$EXTERNALSYM VK_BACK}
VK_BACK = 8;
{$EXTERNALSYM VK_TAB}
VK_TAB = 9;
{$EXTERNALSYM VK_CLEAR}
VK_CLEAR = 12;
{$EXTERNALSYM VK_RETURN}
VK_RETURN = 13;
{$EXTERNALSYM VK_SHIFT}
VK_SHIFT = $10;
{$EXTERNALSYM VK_CONTROL}
VK_CONTROL = 17;
{$EXTERNALSYM VK_MENU}
VK_MENU = 18;
{$EXTERNALSYM VK_PAUSE}
VK_PAUSE = 19;
{$EXTERNALSYM VK_CAPITAL}
VK_CAPITAL = 20;
{$EXTERNALSYM VK_KANA }
VK_KANA = 21;
{$EXTERNALSYM VK_HANGUL }
VK_HANGUL = 21;
{$EXTERNALSYM VK_JUNJA }
VK_JUNJA = 23;
{$EXTERNALSYM VK_FINAL }
VK_FINAL = 24;
{$EXTERNALSYM VK_HANJA }
VK_HANJA = 25;
{$EXTERNALSYM VK_KANJI }
VK_KANJI = 25;
{$EXTERNALSYM VK_CONVERT }
VK_CONVERT = 28;
{$EXTERNALSYM VK_NONCONVERT }
VK_NONCONVERT = 29;
{$EXTERNALSYM VK_ACCEPT }
VK_ACCEPT = 30;
{$EXTERNALSYM VK_MODECHANGE }
VK_MODECHANGE = 31;
{$EXTERNALSYM VK_ESCAPE}
VK_ESCAPE = 27;
{$EXTERNALSYM VK_SPACE}
VK_SPACE = $20;
{$EXTERNALSYM VK_PRIOR}
VK_PRIOR = 33;
{$EXTERNALSYM VK_NEXT}
VK_NEXT = 34;
{$EXTERNALSYM VK_END}
VK_END = 35;
{$EXTERNALSYM VK_HOME}
VK_HOME = 36;
{$EXTERNALSYM VK_LEFT}
VK_LEFT = 37;
{$EXTERNALSYM VK_UP}
VK_UP = 38;
{$EXTERNALSYM VK_RIGHT}
VK_RIGHT = 39;
{$EXTERNALSYM VK_DOWN}
VK_DOWN = 40;
{$EXTERNALSYM VK_SELECT}
VK_SELECT = 41;
{$EXTERNALSYM VK_PRINT}
VK_PRINT = 42;
{$EXTERNALSYM VK_EXECUTE}
VK_EXECUTE = 43;
{$EXTERNALSYM VK_SNAPSHOT}
VK_SNAPSHOT = 44;
{$EXTERNALSYM VK_INSERT}
VK_INSERT = 45;
{$EXTERNALSYM VK_DELETE}
VK_DELETE = 46;
{$EXTERNALSYM VK_HELP}
VK_HELP = 47;
{ VK_0 thru VK_9 are the same as ASCII '0' thru '9' ($30 - $39) }
{ VK_A thru VK_Z are the same as ASCII 'A' thru 'Z' ($41 - $5A) }
{$EXTERNALSYM VK_LWIN}
VK_LWIN = 91;
{$EXTERNALSYM VK_RWIN}
VK_RWIN = 92;
{$EXTERNALSYM VK_APPS}
VK_APPS = 93;
{$EXTERNALSYM VK_NUMPAD0}
VK_NUMPAD0 = 96;
{$EXTERNALSYM VK_NUMPAD1}
VK_NUMPAD1 = 97;
{$EXTERNALSYM VK_NUMPAD2}
VK_NUMPAD2 = 98;
{$EXTERNALSYM VK_NUMPAD3}
VK_NUMPAD3 = 99;
{$EXTERNALSYM VK_NUMPAD4}
VK_NUMPAD4 = 100;
{$EXTERNALSYM VK_NUMPAD5}
VK_NUMPAD5 = 101;
{$EXTERNALSYM VK_NUMPAD6}
VK_NUMPAD6 = 102;
{$EXTERNALSYM VK_NUMPAD7}
VK_NUMPAD7 = 103;
{$EXTERNALSYM VK_NUMPAD8}
VK_NUMPAD8 = 104;
{$EXTERNALSYM VK_NUMPAD9}
VK_NUMPAD9 = 105;
{$EXTERNALSYM VK_MULTIPLY}
VK_MULTIPLY = 106;
{$EXTERNALSYM VK_ADD}
VK_ADD = 107;
{$EXTERNALSYM VK_SEPARATOR}
VK_SEPARATOR = 108;
{$EXTERNALSYM VK_SUBTRACT}
VK_SUBTRACT = 109;
{$EXTERNALSYM VK_DECIMAL}
VK_DECIMAL = 110;
{$EXTERNALSYM VK_DIVIDE}
VK_DIVIDE = 111;
{$EXTERNALSYM VK_F1}
VK_F1 = 112;
{$EXTERNALSYM VK_F2}
VK_F2 = 113;
{$EXTERNALSYM VK_F3}
VK_F3 = 114;
{$EXTERNALSYM VK_F4}
VK_F4 = 115;
{$EXTERNALSYM VK_F5}
VK_F5 = 116;
{$EXTERNALSYM VK_F6}
VK_F6 = 117;
{$EXTERNALSYM VK_F7}
VK_F7 = 118;
{$EXTERNALSYM VK_F8}
VK_F8 = 119;
{$EXTERNALSYM VK_F9}
VK_F9 = 120;
{$EXTERNALSYM VK_F10}
VK_F10 = 121;
{$EXTERNALSYM VK_F11}
VK_F11 = 122;
{$EXTERNALSYM VK_F12}
VK_F12 = 123;
{$EXTERNALSYM VK_F13}
VK_F13 = 124;
{$EXTERNALSYM VK_F14}
VK_F14 = 125;
{$EXTERNALSYM VK_F15}
VK_F15 = 126;
{$EXTERNALSYM VK_F16}
VK_F16 = 127;
{$EXTERNALSYM VK_F17}
VK_F17 = 128;
{$EXTERNALSYM VK_F18}
VK_F18 = 129;
{$EXTERNALSYM VK_F19}
VK_F19 = 130;
{$EXTERNALSYM VK_F20}
VK_F20 = 131;
{$EXTERNALSYM VK_F21}
VK_F21 = 132;
{$EXTERNALSYM VK_F22}
VK_F22 = 133;
{$EXTERNALSYM VK_F23}
VK_F23 = 134;
{$EXTERNALSYM VK_F24}
VK_F24 = 135;
{$EXTERNALSYM VK_NUMLOCK}
VK_NUMLOCK = 144;
{$EXTERNALSYM VK_SCROLL}
VK_SCROLL = 145;
{ VK_L & VK_R - left and right Alt, Ctrl and Shift virtual keys.
Used only as parameters to GetAsyncKeyState() and GetKeyState().
No other API or message will distinguish left and right keys in this way. }
{$EXTERNALSYM VK_LSHIFT}
VK_LSHIFT = 160;

84.菜單勾選/取消完成後關閉計算機

int flg=EWX_FORCE | EWX_POWEROFF;
            bool ok;
            TokPriv1Luid tp;
            IntPtr hproc = GetCurrentProcess();
            IntPtr htok = IntPtr.Zero;
            k = OpenProcessToken(hproc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref   htok);
            tp.Count = 1;
            tp.Luid = 0;
            tp.Attr = SE_PRIVILEGE_ENABLED;
            k = LookupPrivilegeValue(null, SE_SHUTDOWN_NAME, ref   tp.Luid);
            k = AdjustTokenPrivileges(htok, false, ref   tp, 0, IntPtr.Zero, IntPtr.Zero);
            k = ExitWindowsEx(flg, 0);

85.菜單勾選/取消完成後重新啟動計算機

int flg=EWX_FORCE | EWX_REBOOT;
            bool ok;
            TokPriv1Luid tp;
            IntPtr hproc = GetCurrentProcess();
            IntPtr htok = IntPtr.Zero;
            k = OpenProcessToken(hproc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref   htok);
            tp.Count = 1;
            tp.Luid = 0;
            tp.Attr = SE_PRIVILEGE_ENABLED;
            k = LookupPrivilegeValue(null, SE_SHUTDOWN_NAME, ref   tp.Luid);
            k = AdjustTokenPrivileges(htok, false, ref   tp, 0, IntPtr.Zero, IntPtr.Zero);
            k = ExitWindowsEx(flg, 0);

86.菜單勾選/取消完成後注銷計算機

int flg=EWX_FORCE | EWX_LOGOFF;
            bool ok;
            TokPriv1Luid tp;
            IntPtr hproc = GetCurrentProcess();
            IntPtr htok = IntPtr.Zero;
            k = OpenProcessToken(hproc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref   htok);
            tp.Count = 1;
            tp.Luid = 0;
            tp.Attr = SE_PRIVILEGE_ENABLED;
            k = LookupPrivilegeValue(null, SE_SHUTDOWN_NAME, ref   tp.Luid);
            k = AdjustTokenPrivileges(htok, false, ref   tp, 0, IntPtr.Zero, IntPtr.Zero);
            k = ExitWindowsEx(flg, 0);

87.菜單勾選/取消開機自啟動程序
 public void RunWhenStart(bool Started)
        {
string name=%%1;
string path=Application.ExecutablePath;
            RegistryKey HKLM = Registry.LocalMachine;
            RegistryKey Run = HKLM.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
            if (Started == true)
            {
               try
                {
                    Run.SetValue(name, path);
                    HKLM.Close();
                }
                catch (Exception)
                {
                    MessageBox.Show("注冊表修改錯誤(開機自啟未實現)");
              }
            }
            else
            {
                try
                {
                    if (Run.GetValue(name) != null)
                   {
                        Run.DeleteValue(name);
                      HKLM.Close();
                   }
                    else
                        return;
                }
               catch (Exception e)
               {
                   //ExceptionTransact.WriteErrLog(base.GetType().Name, e.Message);
MessageBox(e.Message);
               }
           }
        }

88.菜單勾選/取消自動登錄系統

89.模擬鍵盤輸入字符串
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;
using KenZhang.Free.VirtualInput;
using System.Runtime.InteropServices;

namespace VirtualInputDemo
{
    public partial class Form1 : Form
    {
        public const int INPUT_KEYBOARD = 1;
        public const int KEYEVENTF_KEYUP = 0x0002;
        [DllImport("user32.dll")]
        public static extern UInt32 SendInput(UInt32 nInputs, ref INPUT pInputs, int cbSize);
        [StructLayout(LayoutKind.Explicit)]
        public struct INPUT
        {
            [FieldOffset(0)]
            public Int32 type;
            [FieldOffset(4)]
            public KEYBDINPUT ki;
            [FieldOffset(4)]
            public MOUSEINPUT mi;
            [FieldOffset(4)]
            public HARDWAREINPUT hi;
        }


        [StructLayout(LayoutKind.Sequential)]
        public struct MOUSEINPUT
        {
            public Int32 dx;
            public Int32 dy;
            public Int32 mouseData;
            public Int32 dwFlags;
            public Int32 time;
            public IntPtr dwExtraInfo;
        }
        [StructLayout(LayoutKind.Sequential)]
        public struct KEYBDINPUT
        {
            public Int16 wVk;
            public Int16 wScan;
            public Int32 dwFlags;
            public Int32 time;
            public IntPtr dwExtraInfo;
        }
        [StructLayout(LayoutKind.Sequential)]
        public struct HARDWAREINPUT
        {
            public Int32 uMsg;
            public Int16 wParamL;
            public Int16 wParamH;
        }

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            textBox1.Focus();
            INPUT inDown = new INPUT();
            inDown.type = INPUT_KEYBOARD;
            inDown.ki.wVk = (int)Keys.A;
            //INPUT inUp = new INPUT();
            //inUp.type = INPUT_KEYBOARD;
            //inUp.ki.wVk = (int)Keys.A;
            //inUp.ki.dwFlags = KEYEVENTF_KEYUP;
            SendInput(1, ref  inDown, Marshal.SizeOf(inDown));
            //SendInput(1, ref  inUp, Marshal.SizeOf(inUp));
        }
    }
}

90.提取PDF文件中的文本
xpdf
   public partial class Form1 : Form
    {
        public OpenFileDialog fdlg = 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.操作內存映射文件

    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控制台程序的輸出信息
      delegate void dReadLine(string strLine);
        private void excuteCommand(string strFile, string args, dReadLine onReadLine)
        {
             System.Diagnostics.Process p = new System.Diagnostics.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)
        {
            this.textBox1.Text += strLine + " ";
         }
             excuteCommand("ipconfig", "", new dReadLine(PrintMessage));

93.接受郵件

94.發送郵件
using System;
using System.Net.Sockets;
using System.Net;
using System.Security.Cryptography;
using System.IO;
// 類名:Pop3
// 功能:接收電子郵件

namespace ZTSX.Email
{
/// <summary>
/// Pop3 的摘要說明。
/// </summary>
public class Pop3
{
private string mstrHost     = null; //主機名稱或IP地址
private int mintPort     = 110; //主機的端口號(默認為110)
private TcpClient mtcpClient   = null; //客戶端
private NetworkStream mnetStream = null; //網絡基礎數據流
private StreamReader m_stmReader = null; //讀取字節流
private string mstrStatMessage   = null; //執行STAT命令後得到的消息(從中得到郵件數)

/// <summary>
/// 構造函數
/// </summary>
/// <remarks>一個郵件接收對象</remarks>
public Pop3()
{
}

/// <summary>
/// 構造函數
/// </summary>
/// <param name="host">主機名稱或IP地址</param>
public Pop3(string host)
{
   mstrHost = host;
}

/// <summary>
/// 構造函數
/// </summary>
/// <param name="host">主機名稱或IP地址</param>
/// <param name="port">主機的端口號</param>
/// <remarks>一個郵件接收對象</remarks>
public Pop3(string host,int port)
{
   mstrHost = host;
   mintPort = port;
}

#region 屬性

/// <summary>
/// 主機名稱或IP地址
/// </summary>
/// <remarks>主機名稱或IP地址</remarks>
public string HostName
{
   get{return mstrHost;}
   set{mstrHost = value;}
}

/// <summary>
/// 主機的端口號
/// </summary>
/// <remarks>主機的端口號</remarks>
public int Port
{
   get{return mintPort;}
   set{mintPort = value;}
}

#endregion

#region 私有方法

/// <summary>
/// 向網絡訪問的基礎數據流中寫數據(發送命令碼)
/// </summary>
/// <param name="netStream">可以用於網絡訪問的基礎數據流</param>
/// <param name="command">命令行</param>
/// <remarks>向網絡訪問的基礎數據流中寫數據(發送命令碼)</remarks>
private void WriteToNetStream(ref NetworkStream netStream,String command)
{
   string strToSend = command + "\r\n";
   byte[] arrayToSend = System.Text.Encoding.ASCII.GetBytes(strToSend.ToCharArray());
      netStream.Write(arrayToSend,0,arrayToSend.Length);
}

/// <summary>
/// 檢查命令行結果是否正確
/// </summary>
/// <param name="message">命令行的執行結果</param>
/// <param name="check">正確標志</param>
/// <returns>
/// 類型:布爾
/// 內容:true表示沒有錯誤,false為有錯誤
/// </returns>
/// <remarks>檢查命令行結果是否有錯誤</remarks>
private bool CheckCorrect(string message,string check)
{
   if(message.IndexOf(check) == -1)
    return false;
   else
    return true;
}

/// <summary>
/// 郵箱中的未讀郵件數
/// </summary>
/// <param name="message">執行完LIST命令後的結果</param>
/// <returns>
/// 類型:整型
/// 內容:郵箱中的未讀郵件數
/// </returns>
/// <remarks>郵箱中的未讀郵件數</remarks>
private int GetMailNumber(string message)
{
   string[] strMessage = message.Split(' ');
   return Int32.Parse(strMessage[1]);
}

/// <summary>
/// 得到經過解碼後的郵件的內容
/// </summary>
/// <param name="encodingContent">解碼前的郵件的內容</param>
/// <returns>
/// 類型:字符串
/// 內容:解碼後的郵件的內容
/// </returns>
/// <remarks>得到解碼後的郵件的內容</remarks>
private string GetDecodeMailContent(string encodingContent)
{
   string strContent = encodingContent.Trim();
   string strEncode = null;

   int iStart = strContent.IndexOf("Base64");
   if(iStart == -1)
    throw new Pop3Exception("郵件內容不是Base64編碼,請檢查");
   else
   {
    strEncode = strContent.Substring(iStart + 6,strContent.Length - iStart - 6);
    try
    {
     return SX.Encode.TransformToString(strEncode);
    }
    catch(SX.EncodeException exc)
    {
     throw new Pop3Exception(exc.Message);
    }
   }
}

#endregion

/// <summary>
/// 與主機建立連接
/// </summary>
/// <returns>
/// 類型:布爾
/// 內容:連接結果(true為連接成功,false為連接失敗)
/// </returns>
/// <remarks>與主機建立連接</remarks>
public bool Connect()
{
   if(mstrHost == null)
    throw new Exception("請提供SMTP主機名稱或IP地址!");
   if(mintPort == 0)
    throw new Exception("請提供SMTP主機的端口號");
   try
   {
    mtcpClient = new TcpClient(mstrHost,mintPort);
    mnetStream = mtcpClient.GetStream();
    m_stmReader = new StreamReader(mtcpClient.GetStream());

    string strMessage = m_stmReader.ReadLine();
    if(CheckCorrect(strMessage,"+OK") == true)
     return true;
    else
     return false;
   }
   catch(SocketException exc)
   {
    throw new Pop3Exception(exc.ToString());
   }
   catch(NullReferenceException exc)
   {
    throw new Pop3Exception(exc.ToString());
   }
}

#region Pop3命令

/// <summary>
/// 執行Pop3命令,並檢查執行的結果
/// </summary>
/// <param name="command">Pop3命令行</param>
/// <returns>
/// 類型:字符串
/// 內容:Pop3命令的執行結果
/// </returns>
private string ExecuteCommand(string command)
{
   string strMessage = null; //執行Pop3命令後返回的消息

   try
   {
    //發送命令
    WriteToNetStream(ref mnetStream,command);

    //讀取多行
    if(command.Substring(0,4).Equals("LIST") || command.Substring(0,4).Equals("RETR") || command.Substring(0,4).Equals("UIDL")) //記錄STAT後的消息(其中包含郵件數)
    {
     strMessage = ReadMultiLine();

     if(command.Equals("LIST")) //記錄LIST後的消息(其中包含郵件數)
      mstrStatMessage = strMessage;
    }
     //讀取單行
    else
     strMessage = m_stmReader.ReadLine();

    //判斷執行結果是否正確
    if(CheckCorrect(strMessage,"+OK"))
     return strMessage;
    else
     return "Error";
   }
   catch(IOException exc)
   {
    throw new Pop3Exception(exc.ToString());
   }
}

/// <summary>
/// 在Pop3命令中,LIST、RETR和UIDL命令的結果要返回多行,以點號(.)結尾,
/// 所以如果想得到正確的結果,必須讀取多行
/// </summary>
/// <returns>
/// 類型:字符串
/// 內容:執行Pop3命令後的結果
/// </returns>
private string ReadMultiLine()
{
   string strMessage = m_stmReader.ReadLine();
   string strTemp = null;
   while(strMessage != ".")
   {
    strTemp = strTemp + strMessage;
    strMessage = m_stmReader.ReadLine();
   }
   return strTemp;
}

//USER命令
private string USER(string user)
{
   return ExecuteCommand("USER " + user) + "\r\n";
}

//PASS命令
private string PASS(string password)
{
   return ExecuteCommand("PASS " + password) + "\r\n";
}

//LIST命令
private string LIST()
{
   return ExecuteCommand("LIST") + "\r\n";
}

//UIDL命令
private string UIDL()
{
   return ExecuteCommand("UIDL") + "\r\n";
}

//NOOP命令
private string NOOP()
{
   return ExecuteCommand("NOOP") + "\r\n";
}

//STAT命令
private string STAT()
{
   return ExecuteCommand("STAT") + "\r\n";
}

//RETR命令
private string RETR(int number)
{
   return ExecuteCommand("RETR " + number.ToString()) + "\r\n";
}

//DELE命令
private string DELE(int number)
{
   return ExecuteCommand("DELE " + number.ToString()) + "\r\n";
}

//QUIT命令
private void Quit()
{
   WriteToNetStream(ref mnetStream,"QUIT");
}

/// <summary>
/// 收取郵件
/// </summary>
/// <param name="user">用戶名</param>
/// <param name="password">口令</param>
/// <returns>
/// 類型:字符串數組
/// 內容:解碼前的郵件內容
/// </returns>
private string[] ReceiveMail(string user,string password)
{
   int iMailNumber = 0; //郵件數

   if(USER(user).Equals("Error"))
    throw new Pop3Exception("用戶名不正確!");
   if(PASS(password).Equals("Error"))
    throw new Pop3Exception("用戶口令不正確!");
   if(STAT().Equals("Error"))
    throw new Pop3Exception("准備接收郵件時發生錯誤!");
   if(LIST().Equals("Error"))
    throw new Pop3Exception("得到郵件列表時發生錯誤!");

   try
   {
    iMailNumber = GetMailNumber(mstrStatMessage);

    //沒有新郵件
    if(iMailNumber == 0)
     return null;
    else
    {
     string[] strMailContent = new string[iMailNumber];

     for(int i = 1 ; i <= iMailNumber ; i++)
     {
      //讀取郵件內容
      strMailContent[i - 1] = GetDecodeMailContent(RETR(i));
     }
     return strMailContent;
    }
   }
   catch(Pop3Exception exc)
   {
    throw new Pop3Exception(exc.ToString());
   }
}

#endregion


/// <summary>
/// 收取郵件   
/// </summary>
/// <param name="user">用戶名</param>
/// <param name="password">口令</param>
/// <returns>
/// 類型:字符串數組
/// 內容:解碼前的郵件內容
/// </returns>
///<remarks>收取郵箱中的未讀郵件</remarks>
public string[] Receive(string user,string password)
{
   try
   {
    return ReceiveMail(user,password);
   }
   catch(Pop3Exception exc)
   {
    throw new Pop3Exception(exc.ToString());
   }
}

/// <summary>
/// 斷開所有與服務器的會話
/// </summary>
/// <remarks>斷開所有與服務器的會話</remarks>
public void DisConnect()
{
   try
   {
    Quit();
    if(m_stmReader != null)
     m_stmReader.Close();
    if(mnetStream != null)
     mnetStream.Close();
    if(mtcpClient != null)
     mtcpClient.Close();
   }
   catch(SocketException exc)
   {
    throw new Pop3Exception(exc.ToString());
   }
}

/// <summary>
/// 刪除郵件
/// </summary>
/// <param name="number">郵件號</param>
public void DeleteMail(int number)
{
   //刪除郵件
   int iMailNumber = number + 1;
   if(DELE(iMailNumber).Equals("Error"))
    throw new Pop3Exception("刪除第" + iMailNumber.ToString() + "時出現錯誤!");
}

}
}

95.報表相關

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)
   {
     stringstrPrinterName=@"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.全屏幕截取


[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 myimage = new Bitmap(rect.Width, rect.Height, g);
//第二種得到全屏坐標的方法
         // Image myimage = new Bitmap(Screen.PrimaryScreen.Bounds.Width,Screen.PrimaryScreen.Bounds.Height,g);
//創建以屏幕大小為標准的位圖
            Graphics gg = Graphics.FromImage(myimage);
            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   
            myimage.Save(Application.StartupPath + @"\bob.jpg",    ImageFormat.Jpeg);//以JPG文件格式來保存 
            this.Show();

97.區域截幕

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值

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值

bool b=false;
string path = (%%2.LastIndexOf("\") == %%2.Length - 1) ? %%2 : %%2 + "\";
string parent = Path.GetDirectoryName(%%1);
Directory.CreateDirectory(path + Path.GetFileName(%%1));
DirectoryInfo dir = new DirectoryInfo((%%1.LastIndexOf("\") == %%1.Length - 1) ? %%1 : %%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 (b && f == null)
    {
        DirectoryInfo d = tmp as DirectoryInfo;
        Directory.CreateDirectory(d.FullName.Replace((parent.LastIndexOf("\") == parent.Length - 1) ? parent : parent + "\", 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();
    }
}
 

摘自  programming lover
 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved