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

c#文件操作大全(一)

編輯:C#入門知識

1.創建文件夾
//using System.IO;
Directory.CreateDirectory(%%1);

2.創建文件
//using System.IO;
File.Create(%%1);

3.刪除文件
//using System.IO;
File.Delete(%%1);

4.刪除文件夾
//using System.IO;
Directory.Delete(%%1);

5.刪除一個目錄下所有的文件夾
//using System.IO;
foreach (string dirStr in Directory.GetDirectories(%%1))
{
 DirectoryInfo dir = new DirectoryInfo(dirStr);
 ArrayList folders=new ArrayList();
 FileSystemInfo[] fileArr = dir.GetFileSystemInfos();
 for (int i = 0; i < folders.Count; i++)
 {
  FileInfo f = folders[i] as FileInfo;
  if (f == null)
  {
   DirectoryInfo d = folders[i] as DirectoryInfo;
   d.Delete();
  }
 }
}

6.清空文件夾
//using System.IO;
Directory.Delete(%%1,true);
Directory.CreateDirectory(%%1);

7.讀取文件
//using System.IO;
StreamReader s = File.OpenText(%%1);
string %%2 = null;
while ((%%2 = s.ReadLine()) != null){
 %%3
}
s.Close();

8.寫入文件
//using System.IO;
FileInfo f = new FileInfo(%%1);
StreamWriter w = f.CreateText();
w.WriteLine(%%2);
w.Close();

9.寫入隨機文件
//using System.IO;
byte[] dataArray = new byte[100000];//new Random().NextBytes(dataArray);
using(FileStream FileStream = new FileStream(%%1, FileMode.Create)){
// Write the data to the file, byte by byte.
 for(int i = 0; i < dataArray.Length; i++){
  FileStream.WriteByte(dataArray[i]);
 }
// Set the stream position to the beginning of the file.
 FileStream.Seek(0, SeekOrigin.Begin);
// Read and verify the data.
 for(int i = 0; i < FileStream.Length; i++){
  if(dataArray[i] != FileStream.ReadByte()){
   //寫入數據錯誤
   return;
  }
 }
//"數據流"+FileStream.Name+"已驗證"
}

10.讀取文件屬性
//using System.IO;
FileInfo f = new FileInfo(%%1);//f.CreationTime,f.FullName
if((f.Attributes & FileAttributes.ReadOnly) != 0){
 %%2
}
else{
 %%3
}

11.寫入屬性
//using System.IO;
FileInfo f = new FileInfo(%%1);
//設置只讀
f.Attributes = myFile.Attributes | FileAttributes.ReadOnly;
//設置可寫
f.Attributes = myFile.Attributes & ~FileAttributes.ReadOnly;

12.枚舉一個文件夾中的所有文件夾
//using System.IO;
foreach (string %%2 in Directory.GetDirectories(%%1)){
 %%3
}


13.復制文件夾

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 (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
                    {
                        f.CopyTo(f.FullName.Replace(parent, path));
                    }
}

14.復制目錄下所有的文件夾到另一個文件夾下

DirectoryInfo d = new DirectoryInfo(%%1);
foreach (DirectoryInfo dirs in d.GetDirectories())
{
    Queue<FileSystemInfo> al = new Queue<FileSystemInfo>(dirs.GetFileSystemInfos());
    while (al.Count > 0)
    {
        FileSystemInfo temp = al.Dequeue();
        FileInfo file = temp as FileInfo;
        if (file == null)
        {
            DirectoryInfo directory = temp as DirectoryInfo;
            Directory.CreateDirectory(path + directory.Name);
            foreach (FileSystemInfo fsi in directory.GetFileSystemInfos())
                al.Enqueue(fsi);
        }
        else
            File.Copy(file.FullName, path + file.Name);
    }
}

15.移動文件夾

                string filename = Path.GetFileName(%%1);
                string path=(%%2.LastIndexOf("\") == %%2.Length - 1) ? %%2 : %%2 + "\";
                if (Path.GetPathRoot(%%1) == Path.GetPathRoot(%%2))
                    Directory.Move(%%1, path + filename);
                else
                {
                    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 (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);
                }

16.移動目錄下所有的文件夾到另一個目錄下

string filename = Path.GetFileName(%%1);
                if (Path.GetPathRoot(%%1) == Path.GetPathRoot(%%2))
                    foreach (string dir in Directory.GetDirectories(%%1))
                        Directory.Move(dir, Path.Combine(%%2,filename));
                else
                {
                    foreach (string dir2 in Directory.GetDirectories(%%1))
                    {
                        string parent = Path.GetDirectoryName(dir2);
                        Directory.CreateDirectory(Path.Combine(%%2, 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 + "\", %%2));
                                dpath.Create();
                                foreach (FileSystemInfo fi in d.GetFileSystemInfos())
                                {
                                    Folders.Enqueue(fi);
                                }
                            }
                            else
                            {
                                f.MoveTo(f.FullName.Replace(parent, %%2));
                            }
                        }
                        dirdir.Delete(true);
                    }
                }

17.以一個文件夾的框架在另一個目錄創建文件夾和空文件

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 (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));
    }
}

18.復制文件
//using System.IO;
File.Copy(%%1,%%2);

19.復制一個文件夾下所有的文件到另一個目錄
//using System.IO;
foreach (string fileStr in Directory.GetFiles(%%1))
 File.Copy((%%1.LastIndexOf("\") == %%1.Length - 1) ? %%1 +Path.GetFileName(fileStr): %%1 + "\"+Path.GetFileName(fileStr),(%%2.LastIndexOf("\\") == %%2.Length - 1) ? %%2 +Path.GetFileName(fileStr): %%2 + "\"+Path.GetFileName(fileStr));

20.提取擴展名
//using System.IO;
string %%2=Path.GetExtension(%%1);

21.提取文件名
//using System.IO;
string %%2=Path.GetFileName(%%1);

22.提取文件路徑
//using System.IO;
string %%2=Path.GetDirectoryName(%%1);

23.替換擴展名
//using System.IO;
File.ChangeExtension(%%1,%%2);

24.追加路徑
//using System.IO;
string %%3=Path.Combine(%%1,%%2);

25.移動文件
//using System.IO;
File.Move(%%1,%%2+"\"+file.getname(%%1));

26.移動一個文件夾下所有文件到另一個目錄
foreach (string fileStr in Directory.GetFiles(%%1))
 File.Move((%%1.LastIndexOf("\") == %%1.Length - 1) ? %%1 +Path.GetFileName(fileStr): %%1 + "\"+Path.GetFileName(fileStr),(%%2.LastIndexOf("\\") == %%2.Length - 1) ? %%2 +Path.GetFileName(fileStr): %%2 + "\"+Path.GetFileName(fileStr));

27.指定目錄下搜索文件

string fileName=%%1;
string dirName=%%2;
 DirectoryInfo   dirc=new   DirectoryInfo(dirName);
 foreach(FileInfo   file   in   dirc.GetFiles()) {
  if(file.Name.IndexOf(fileName)>-1)
   return file.FullName;
  }
  foreach(DirectoryInfo   dir   in   dirc.GetDirectories())   { 
   return   GetFile(fileName,dir.FullName); 
  }
  return   "找不到指定的文件"; 
 }

28.打開對話框
OpenFileDialog penFileDialog=new OpenFileDialog();
openFileDialog.InitialDirectory="c:\\\\";//注意這裡寫路徑時要用c:\\\\而不是c:\\
openFileDialog.Filter="文本文件|*.*|C#文件|*.cs|所有文件|*.*";
openFileDialog.RestoreDirectory=true;
openFileDialog.FilterIndex=1;
if (openFileDialog.ShowDialog()==DialogResult.OK) {
 fName=openFileDialog.FileName;
 File fileOpen=new File(fName);
 isFileHaveName=true;
 %%1=fileOpen.ReadFile();
 %%1.AppendText("");
}

29.文件分割
//using System.IO;
FileStream fsr = new FileStream(%%1, FileMode.Open, FileAccess.Read);
byte[] btArr = new byte[fsr.Length];
fsr.Read(btArr, 0, btArr.Length);
fsr.Close();
string strFileName=%%1.Substring(%%1.LastIndexOf("\")+1);
FileStream fsw = new FileStream(%%2 + strFileName + "1", FileMode.Create, FileAccess.Write);
fsw.Write(btArr, 0, btArr.Length/2);
fsw.Close();
fsw = new FileStream(%%2 + strFileName + "2", FileMode.Create, FileAccess.Write);
fsw.Write(btArr, btArr.Length/2, btArr.Length-btArr.Length/2);
fsw.Close();

30.文件合並
//using System.IO;
string strFileName = %%1.Substring(%%1.LastIndexOf("\") + 1);
FileStream fsr1 = new FileStream(%%2 + strFileName + "1", FileMode.Open, FileAccess.Read);
FileStream fsr2 = new FileStream(%%2 + strFileName + "2", FileMode.Open, FileAccess.Read);
byte[] btArr = new byte[fsr1.Length+fsr2.Length];
fsr1.Read(btArr, 0, Convert.ToInt32(fsr1.Length));
fsr2.Read(btArr, Convert.ToInt32(fsr1.Length), Convert.ToInt32(fsr2.Length));
fsr1.Close();fsr2.Close();
FileStream fsw = new FileStream(%%2 + strFileName, FileMode.Create, FileAccess.Write);
fsw.Write(btArr, 0, btArr.Length);
fsw.Close();

31.文件簡單加密
//using System.IO;
//讀文件
FileStream fsr = new FileStream(%%1, FileMode.Open, FileAccess.Read);
byte[] btArr = new byte[fsr.Length];
fsr.Read(btArr, 0, btArr.Length);
fsr.Close();
for (int i = 0; i < btArr.Length; i++){ //加密
 int ibt = btArr[i];
 ibt += 100;
 ibt %= 256;
 btArr[i] = Convert.ToByte(ibt);
}
//寫文件
string strFileName = Path.GetExtension(%%1);
FileStream fsw = new FileStream(%%2+"/" + "enc_" + strFileName, FileMode.Create, FileAccess.Write);
 fsw.Write(btArr, 0, btArr.Length);
 fsw.Close();

32.文件簡單解密
//using System.IO;
FileStream fsr = new FileStream(%%1, FileMode.Open, FileAccess.Read);
byte[] btArr = new byte[fsr.Length];
fsr.Read(btArr, 0, btArr.Length);
fsr.Close();
for (int i = 0; i < btArr.Length; i++){ //解密
 int ibt = btArr[i];
 ibt -= 100;
 ibt += 256;
 ibt %= 256;
 btArr[i] = Convert.ToByte(ibt);
}
//寫文件
string strFileName = Path.GetExtension(%%1);
FileStream fsw = new FileStream(%%2 +"/" + strFileName, FileMode.Create, FileAccess.Write);
fsw.Write(btArr, 0, btArr.Length);
fsw.Close();

33.讀取ini文件屬性
//using System.Runtime.InteropServices;
//[DllImport("kernel32")]//返回取得字符串緩沖區的長度
//private static extern long GetPrivateProfileString(string section,string key, string def,StringBuilder retVal,int size,string filePath);
string Section=%%1;
string Key=%%2;
string NoText=%%3;
string iniFilePath="Setup.ini";
string %%4=String.Empty;
 if(File.Exists(iniFilePath)){
  StringBuilder temp = new StringBuilder(1024);
  GetPrivateProfileString(Section,Key,NoText,temp,1024,iniFilePath);
  %%4=temp.ToString();
 }

34.合並一個目錄下所有的文件
//using System.IO;
FileStream fsw = new FileStream(%%2, FileMode.Create, FileAccess.Write);
foreach (string fileStr in Directory.GetFiles(%%1))
{
FileStream fsr1 = new FileStream(fileStr, FileMode.Open, FileAccess.Read);
byte[] btArr = new byte[fsr1.Length];
fsr1.Read(btArr, 0, Convert.ToInt32(fsr1.Length));
fsr1.Close();
fsw.Write(btArr, 0, btArr.Length);
}
fsw.Close();

35.寫入ini文件屬性
//using System.Runtime.InteropServices;
//[DllImport("kernel32")]//返回0表示失敗,非0為成功
//private static extern long WritePrivateProfileString(string section,string key, string val,string filePath);
string Section=%%1;
string Key=%%2;
string Value=%%3;
string iniFilePath="Setup.ini";
bool %%4=false;
    if(File.Exists(iniFilePath))
    {
long pStation = WritePrivateProfileString(Section,Key,Value,iniFilePath);  
if(OpStation == 0)
{
    %%4=false;
}
else
{
    %%4=true;
}
    }

36.獲得當前路徑
string %%1=Environment.CurrentDirectory;

37.讀取XML數據庫
//using System.Xml;
XmlDocument doc=new XmlDocument();
doc.Load(%%1);
string %%9;
XmlElement xe=doc.GetElementById(%%7);
XmlNodeList elemList=xe.ChildNodes;
foreach(XmlNode elem in elemList)
{
if(elem.NodeType==%%8)
{
%%9=elem.Value;
break;
}
}

38.寫入XML數據庫
//using System.Xml;
XmlDocument doc=new XmlDocument();
doc.Load(%%1);
XmlNode root=doc.DocumentElement;
XmlElement book=doc.createElement_x(%%3);
XmlElement book=doc.createElement_x(%%5);
XmlElement port=doc.createElement_x(%%6);
book.SetAttribute(%%4,root.ChildNodes.Count.ToString());
author.InnerText=%%8;
book.appendChild(author);
book.appendChild(port);
root.appendChild(book);
doc.Save(%%1);

39.ZIP壓縮文件

FileStream infile;
try
{
 // Open the file as a FileStream object.
 infile = new FileStream(%%1, FileMode.Open, FileAccess.Read, FileShare.Read);
 byte[] buffer = new byte[infile.Length];
 // Read the file to ensure it is readable.
 int count = infile.Read(buffer, 0, buffer.Length);
 if (count != buffer.Length)
 {
  infile.Close();
//Test Failed: Unable to read data from file
  return;
 }
 infile.Close();
 MemoryStream ms = new MemoryStream();
 // Use the newly created memory stream for the compressed data.
 DeflateStream compressedzipStream = new DeflateStream(ms, CompressionMode.Compress, true);
 //Compression
 compressedzipStream.Write(buffer, 0, buffer.Length);
 // Close the stream.
 compressedzipStream.Close();
 //Original size: {0}, Compressed size: {1}", buffer.Length, ms.Length);
 FileInfo f = new FileInfo(%%2);
 StreamWriter w = f.CreateText();
 w.Write(buffer,0,ms.Length);
 w.Close();
} // end try
catch (InvalidDataException)
{
 //Error: The file being read contains invalid data.
} catch (FileNotFoundException)
{
 //Error:The file specified was not found.
} catch (ArgumentException)
{
 //Error: path is a zero-length string, contains only white space, or contains one or more invalid characters
} catch (PathTooLongException)
{
 //Error: The specified path, file name, or both exceed the system-defined maximum length. For example, on Windows-based

 platforms, paths must be less than 248 characters, and file names must be less than 260 characters.
} catch (DirectoryNotFoundException)
{
 //Error: The specified path is invalid, such as being on an unmapped drive.
} catch (IOException)
{
 //Error: An I/O error occurred while opening the file.
} catch (UnauthorizedAccessException)
{
 //Error: path specified a file that is read-only, the path is a directory, or caller does not have the required

 permissions.
} catch (IndexOutOfRangeException)
{
 //Error: You must provide parameters for MyGZIP.
}

40.ZIP解壓縮

FileStream infile;
try
{
    // Open the file as a FileStream object.
    infile = new FileStream(%%1, FileMode.Open, FileAccess.Read, FileShare.Read);
    byte[] buffer = new byte[infile.Length];
    // Read the file to ensure it is readable.
    int count = infile.Read(buffer, 0, buffer.Length);
    if (count != buffer.Length)
    {
infile.Close();
//Test Failed: Unable to read data from file
return;
    }
    infile.Close();
    MemoryStream ms = new MemoryStream();
    // ms.Position = 0;
    DeflateStream zipStream = new DeflateStream(ms, CompressionMode.Decompress);
    //Decompression
    byte[] decompressedBuffer = new byte[buffer.Length *2];
    zipStream.Close();
FileInfo f = new FileInfo(%%2);
StreamWriter w = f.CreateText();
w.Write(decompressedBuffer);
w.Close();
} // end try
catch (InvalidDataException)
{
    //Error: The file being read contains invalid data.
}
catch (FileNotFoundException)
{
    //Error:The file specified was not found.
}
catch (ArgumentException)
{
    //Error: path is a zero-length string, contains only white space, or contains one or more invalid characters
}
catch (PathTooLongException)
{
    //Error: The specified path, file name, or both exceed the system-defined maximum length. For example, on Windows-based

platforms, paths must be less than 248 characters, and file names must be less than 260 characters.
}
catch (DirectoryNotFoundException)
{
    //Error: The specified path is invalid, such as being on an unmapped drive.
}
catch (IOException)
{
    //Error: An I/O error occurred while opening the file.
}
catch (UnauthorizedAccessException)
{
    //Error: path specified a file that is read-only, the path is a directory, or caller does not have the required

permissions.
}
catch (IndexOutOfRangeException)
{
    //Error: You must provide parameters for MyGZIP.
}

41.獲得應用程序完整路徑
string %%1=Application.ExecutablePath;

42.ZIP壓縮文件夾

        private void CreateCompressFile(Stream source, string destinationName)
        {
            using (Stream destination = new FileStream(destinationName, FileMode.Create, FileAccess.Write))
            {
                using (GZipStream utput = new GZipStream(destination, CompressionMode.Compress))
                {
                    byte[] bytes = new byte[4096];
                    int n;
                    while ((n = source.Read(bytes, 0, bytes.Length)) != 0)
                    {
                        output.Write(bytes, 0, n);
                    }
                }
            }
        }
ArrayList list = new ArrayList();
foreach (string f in Directory.GetFiles(%%1))
{
    byte[] destBuffer = File.ReadAllBytes(f);
    SerializeFileInfo sfi = new SerializeFileInfo(f, destBuffer);
    list.Add(sfi);
}
IFormatter formatter = new BinaryFormatter();
using (Stream s = new MemoryStream())
{
    formatter.Serialize(s, list);
    s.Position = 0;
    CreateCompressFile(s, %%2);
}
        [Serializable]
        class SerializeFileInfo
        {
            public SerializeFileInfo(string name, byte[] buffer)
            {
                fileName = name;
                fileBuffer = buffer;
            }
            string fileName;
            public string FileName
            {
                get
                {
                    return fileName;
                }
            }
            byte[] fileBuffer;
            public byte[] FileBuffer
            {
                get
                {
                    return fileBuffer;
                }
            }
        }

43.遞歸刪除目錄下的文件
//using System.IO;
DirectoryInfo DInfo=new DirectoryInfo(%%1);
FileSystemInfo[] FSInfo=DInfo.GetFileSystemInfos();
for(int i=0;i<FSInfo.Length;i++)
{
FileInfo FInfo=new FileInfo(%%1+FSInfo[i].ToString());
FInfo.Delete();
}

44.驗證DTD

XmlReaderSettings settings = new XmlReaderSettings();
settings.ProhibitDtd = false;
settings.ValidationType = ValidationType.DTD;
settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);
// Create the XmlReader object.
XmlReader reader = XmlReader.Create("my book.xml", settings);
// Parse the file.
while (reader.Read());
// Display any validation errors.
private static void ValidationCallBack(object sender, ValidationEventArgs e)
{
Console.WriteLine("Validation Error: {0}", e.Message);
}

45.Schema 驗證

Boolean m_success;
XmlValidatingReader reader = null;
   XmlSchemaCollection myschema = new XmlSchemaCollection();
ValidationEventHandler eventHandler = new ValidationEventHandler(ShowCompileErrors);
try
{
//Create the XML fragment to be parsed.
String xmlFrag = "<author xmlns='urn:bookstore- schema'xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>" +
"<first-name>Herman</first-name>" +
"<last-name>Melville</last-name>" +
"</author>";
//Create the XmlParserContext.
XmlParserContext context = new XmlParserContext(null, null, "", XmlSpace.None);
//Implement the reader.
reader = new XmlValidatingReader(xmlFrag, XmlNodeType.Element, context);
//Add the schema.
myschema.Add("urn:bookstore-schema", "c:\\Books.xsd");
//Set the schema type and add the schema to the reader.
reader.ValidationType = ValidationType.Schema;
reader.Schemas.Add(myschema);
while (reader.Read())
{
}
Console.WriteLine("Completed validating xmlfragment");
}
catch (XmlException XmlExp)
{
Console.WriteLine(XmlExp.Message);
}
catch(XmlSchemaException XmlSchExp)
{
Console.WriteLine(XmlSchExp.Message);
}
catch(Exception GenExp)
{
Console.WriteLine(GenExp.Message);
}
finally
{
Console.Read();
}
public static void ShowCompileErrors(object sender, ValidationEventArgs args)
{
Console.WriteLine("Validation Error: {0}", args.Message);
}

46.Grep

//Traditionally grep stands for "Global Regular Expression Print".
//Global means that an entire file is searched.
//Regular Expression means that a regular expression string is used to establish a search pattern.
//Print means that the command will display its findings.
//Simply put, grep searches an entire file for the pattern you want and displays its findings.
//
//The use syntax is different from the traditional Unix syntax, I prefer a syntax similar to
//csc, the C# compiler.
//
// grep [/h|/H] - Usage Help
//
// grep [/c] [/i] [/l] [/n] [/r] /E:reg_exp /F:files
//
// /c - print a count of matching lines for each input file;
// /i - ignore case in pattern;
// /l - print just files (scanning will stop on first match);
// /n - prefix each line of output with line number;
// /r - recursive search in subdirectories;
//
// /E:reg_exp - the Regular Expression used as search pattern. The Regular Expression can be delimited by
// quotes like "..." and '...' if you want to include in it leading or trailing blanks;
//
// /F:files - the list of input files. The files can be separated by commas as in /F:file1,file2,file3
//and wildcards can be used for their specification as in /F:*file?.txt;
//
//Example:
//
// grep /c /n /r /E:" C Sharp " /F:*.cs
//Option Flags
private bool m_bRecursive;
private bool m_bIgnoreCase;
private bool m_bJustFiles;
private bool m_bLineNumbers;
private bool m_bCountLines;
private string m_strRegEx;
private string m_strFiles;
//ArrayList keeping the Files
private ArrayList m_arrFiles = new ArrayList();
//Properties
public bool Recursive
{
get { return m_bRecursive; }
set { m_bRecursive = value; }
}

public bool IgnoreCase
{
get { return m_bIgnoreCase; }
set { m_bIgnoreCase = value; }
}

public bool JustFiles
{
get { return m_bJustFiles; }
set { m_bJustFiles = value; }
}

public bool LineNumbers
{
get { return m_bLineNumbers; }
set { m_bLineNumbers = value; }
}

public bool CountLines
{
get { return m_bCountLines; }
set { m_bCountLines = value; }
}

public string RegEx
{
get { return m_strRegEx; }
set { m_strRegEx = value; }
}

public string Files
{
get { return m_strFiles; }
set { m_strFiles = value; }
}

//Build the list of Files
private void GetFiles(String strDir, String strExt, bool bRecursive)
{
//search pattern can include the wild characters '*' and '?'
string[] fileList = Directory.GetFiles(strDir, strExt);
for(int i=0; i<fileList.Length; i++)
{
if(File.Exists(fileList[i]))
m_arrFiles.Add(fileList[i]);
}
if(bRecursive==true)
{
//Get recursively from subdirectories
string[] dirList = Directory.GetDirectories(strDir);
for(int i=0; i<dirList.Length; i++)
{
GetFiles(dirList[i], strExt, true);
}
}
}

//Search Function
public void Search()
{
String strDir = Environment.CurrentDirectory;
//First empty the list
m_arrFiles.Clear();
//Create recursively a list with all the files complying with the criteria
String[] astrFiles = m_strFiles.Split(new Char[] {','});
for(int i=0; i<astrFiles.Length; i++)
{
//Eliminate white spaces
astrFiles[i] = astrFiles[i].Trim();
GetFiles(strDir, astrFiles[i], m_bRecursive);
}
//Now all the Files are in the ArrayList, open each one
//iteratively and look for the search string
String strResults = "Grep Results:\r\n\r\n";
String strLine;
int iLine, iCount;
bool bEmpty = true;
IEnumerator enm = m_arrFiles.GetEnumerator();
while(enm.MoveNext())
{
try
{
StreamReader sr = File.OpenText((string)enm.Current);
iLine = 0;
iCount = 0;
bool bFirst = true;
while((strLine = sr.ReadLine()) != null)
{
iLine++;
//Using Regular Expressions as a real Grep
Match mtch;
if(m_bIgnoreCase == true)
mtch = Regex.Match(strLine, m_strRegEx, RegexOptions.IgnoreCase);
else
mtch = Regex.Match(strLine, m_strRegEx);
if(mtch.Success == true)
{
bEmpty = false;
iCount++;
if(bFirst == true)
{
if(m_bJustFiles == true)
{
strResults += (string)enm.Current + "\r\n";
break;
}
else
strResults += (string)enm.Current + ":\r\n";
bFirst = false;
}
//Add the Line to Results string
if(m_bLineNumbers == true)
strResults += " " + iLine + ": " + strLine + "\r\n";
else
strResults += " " + strLine + "\r\n";
}
}
sr.Close();
if(bFirst == false)
{
if(m_bCountLines == true)
strResults += " " + iCount + " Lines Matched\r\n";
strResults += "\r\n";
}
}
catch(SecurityException)
{
strResults += "\r\n" + (string)enm.Current + ": Security Exception\r\n\r\n";
}
catch(FileNotFoundException)
{
strResults += "\r\n" + (string)enm.Current + ": File Not Found Exception\r\n";
}
}
if(bEmpty == true)
Console.WriteLine("No matches found!");
else
Console.WriteLine(strResults);
}

//Print Help
private static void PrintHelp()
{
Console.WriteLine("Usage: grep [/h|/H]");
Console.WriteLine("       grep [/c] [/i] [/l] [/n] [/r] /E:reg_exp /F:files");
}

Arguments CommandLine = new Arguments(args);
if(CommandLine["h"] != null || CommandLine["H"] != null)
{
PrintHelp();
return;
}
// The working object
ConsoleGrep grep = new ConsoleGrep();
// The arguments /e and /f are mandatory
if(CommandLine["E"] != null)
grep.RegEx = (string)CommandLine["E"];
else
{
Console.WriteLine("Error: No Regular Expression specified!");
Console.WriteLine();
PrintHelp();
return;
}
if(CommandLine["F"] != null)
grep.Files = (string)CommandLine["F"];
else
{
Console.WriteLine("Error: No Search Files specified!");
Console.WriteLine();
PrintHelp();
return;
}
grep.Recursive = (CommandLine["r"] != null);
grep.IgnoreCase = (CommandLine["i"] != null);
grep.JustFiles = (CommandLine["l"] != null);
if(grep.JustFiles == true)
grep.LineNumbers = false;
else
grep.LineNumbers = (CommandLine["n"] != null);
if(grep.JustFiles == true)
grep.CountLines = false;
else
grep.CountLines = (CommandLine["c"] != null);
// Do the search
grep.Search();

47.直接創建多級目錄
//using System.IO;
DirectoryInfo di=new DirectoryInfo(%%1);
di.CreateSubdirectory(%%2);

48.批量重命名
//using System.IO;
string strOldFileName; string strNewFileName; string strOldPart =this.textBox1.Text.Trim();//重命名文件前的文件名等待替換字符串
string strNewPart = this.textBox2.Text.Trim();//重命名文件後的文件名替換字符串
string strNewFilePath;
string strFileFolder;    //原始圖片目錄
int TotalFiles = 0; DateTime StartTime = DateTime.Now; //獲取開始時間 
FolderBrowserDialog f1 = new FolderBrowserDialog(); //打開選擇目錄對話框
if (f1.ShowDialog() == DialogResult.OK) {
 strFileFolder = f1.SelectedPath;
 DirectoryInfo di = new DirectoryInfo(strFileFolder);
 FileInfo[] filelist = di.GetFiles("*.*");
 int i = 0;
 foreach (FileInfo fi in filelist) {
  strOldFileName = fi.Name;
  strNewFileName = fi.Name.Replace(strOldPart, strNewPart);
  strNewFilePath = @strFileFolder + "\" + strNewFileName;
  filelist[i].MoveTo(@strNewFilePath); TotalFiles += 1;
  this.listBox1.Items.Add("文件名:" + strOldFileName + "已重命名為" + strNewFileName);
  i += 1;
 }
}
DateTime EndTime = DateTime.Now;//獲取結束時間
TimeSpan ts = EndTime - StartTime; this.listBox1.Items.Add("總耗時:" + ts.Hours.ToString() + "時" +ts.Minutes.ToString() + "分" + ts.Seconds.ToString() + "秒");

49.文本查找替換

            if (args.Length == 3)
            {
ReplaceFiles(args[0],args[1],args[2],null);
            }

            if (args.Length == 4)
            {
if (args[3].Contains("v"))
{
    ReplaceVariable(args[0], args[1], args[2], args[3]);
}
else
{
    ReplaceFiles(args[0], args[1], args[2], args[3]);
}
            }

        /// <summary>
        /// 替換環境變量中某個變量的文本值。可以是系統變量,用戶變量,臨時變量。替換時會覆蓋原始值。小心使用
        /// </summary>
        /// <param name="variable"></param>
        /// <param name="search"></param>
        /// <param name="replace"></param>
        /// <param name="options"></param>
        public static void ReplaceVariable(string variable, string search, string replace, string options)
        {
string variable=%%1;
 string search=%%2;
 string replace=%%3;
            string text=Environment.GetEnvironmentVariable(variable);
            System.Windows.Forms.MessageBox.Show(text);
            text=ReplaceText(text, search, replace, options);
            Environment.SetEnvironmentVariable(variable, text);
            text = Environment.GetEnvironmentVariable(variable);
            System.Windows.Forms.MessageBox.Show(text);
        }

 

        /// <summary>
        /// 批量替換文件文本
        /// </summary>
        /// <param name="args"></param>
        public static void ReplaceFiles(string path,string search, string replace, string options)
        {
string path=%%1;
string search=%%2;
string replace=%%3;
            string[] fs;
            if(File.Exists(path)){
ReplaceFile(path, search, replace, options);
return;
            }
            if (Directory.Exists(path))
            {
fs = Directory.GetFiles(path);
foreach (string f in fs)
{

    ReplaceFile(f, search, replace, options);
}
return;
            }
            int i=path.LastIndexOf("");
            if(i<0)i=path.LastIndexOf("/");
            string d, searchfile;
            if (i > -1)
            {
d = path.Substring(0, i + 1);
searchfile = path.Substring(d.Length);
            }
            else
            {
d = System.Environment.CurrentDirectory;
searchfile = path;
            }

            searchfile = searchfile.Replace(".", @".");
            searchfile = searchfile.Replace("?", @"[^.]?");
            searchfile = searchfile.Replace("*", @"[^.]*");
            //System.Windows.Forms.MessageBox.Show(d);  System.Windows.Forms.MessageBox.Show(searchfile);
            if (!Directory.Exists(d)) return;
            fs = Directory.GetFiles(d);
            foreach (string f in fs)
            {
if(System.Text.RegularExpressions.Regex.IsMatch(f,searchfile))
    ReplaceFile(f, search, replace, options);
            }
        }
      
        /// <summary>
        /// 替換單個文本文件中的文本
        /// </summary>
        /// <param name="filename"></param>
        /// <param name="search"></param>
        /// <param name="replace"></param>
        /// <param name="options"></param>
        /// <returns></returns>
        public static bool ReplaceFile(string filename, string search, string replace,string options)
        {
string path=%%1;
string search=%%2;
string replace=%%3;
            FileStream fs = File.OpenRead(filename);
            //判斷文件是文本文件還二進制文件。該方法似乎不科學
            byte b;
            for (long i = 0; i < fs.Length; i++)
            {
b = (byte)fs.ReadByte();
if (b == 0)
{
    System.Windows.Forms.MessageBox.Show("非文本文件");
    return false;//有此字節則表示改文件不是文本文件。就不用替換了
}
            }
            //判斷文本文件編碼規則。
            byte[] bytes = new byte[2];
            Encoding coding=Encoding.Default;
            if (fs.Read(bytes, 0, 2) > 2)
            {
if (bytes == new byte[2] { 0xFF, 0xFE }) coding = Encoding.Unicode;
if (bytes == new byte[2] { 0xFE, 0xFF }) coding = Encoding.BigEndianUnicode;
if (bytes == new byte[2] { 0xEF, 0xBB }) coding = Encoding.UTF8;
            }
            fs.Close();
            //替換數據
            string text=File.ReadAllText(filename, coding);
            text=ReplaceText(text,search, replace, options);
            File.WriteAllText(filename, text, coding);
            return true;
        }
        /// <summary>
        /// 替換文本
        /// </summary>
        /// <param name="text"></param>
        /// <param name="search"></param>
        /// <param name="replace"></param>
        /// <param name="options"></param>
        /// <returns></returns>
        public static string ReplaceText(string text, string search, string replace, string options)
        {
            RegexOptions ps = RegexOptions.None;
            if (options == null)  //純文本替換
            {
search = search.Replace(".", @".");
search = search.Replace("?", @"?");
search = search.Replace("*", @"*");
search = search.Replace("(", @"(");
search = search.Replace(")", @")");
search = search.Replace("[", @"[");
search = search.Replace("[", @"[");
search = search.Replace("[", @"[");
search = search.Replace("{", @"{");
search = search.Replace("}", @"}");
ops |= RegexOptions.IgnoreCase;
            }
            else
            {
if(options.Contains("I"))ops |= RegexOptions.IgnoreCase;
            }
            text = Regex.Replace(text, search, replace, ops);
            return text;
        }

50.文件關聯
//using Microsoft.Win32;
string keyName;
string keyValue;
keyName = %%1; //"WPCFile"
keyValue = %%2; //"資源包文件"
RegistryKey isExCommand = null;
bool isCreateRegistry = true;
try
{
    /// 檢查 文件關聯是否創建
    isExCommand = Registry.ClassesRoot.OpenSubKey(keyName);
    if (isExCommand == null)
    {
        isCreateRegistry = true;
    }
    else
    {
        if (isExCommand.GetValue("Create").ToString() == Application.ExecutablePath.ToString())
        {
            isCreateRegistry = false;
        }
        else
        {
            Registry.ClassesRoot.DeleteSubKeyTree(keyName);
            isCreateRegistry = true;           
        }

    }
}
catch (Exception)
{
    isCreateRegistry = true;
}

if (isCreateRegistry)
{
    try
    {
        RegistryKey key, keyico;
        key = Registry.ClassesRoot.CreateSubKey(keyName);
        key.SetValue("Create", Application.ExecutablePath.ToString());
        keyico = key.CreateSubKey("DefaultIcon");
        keyico.SetValue("", Application.ExecutablePath + ",0");
        key.SetValue("", keyValue);
        key = key.CreateSubKey("Shell");
        key = key.CreateSubKey("Open");
        key = key.CreateSubKey("Command");
        key.SetValue("", """ + Application.ExecutablePath.ToString() + "" "%1"");
        keyName = %%3; //".wpc"
        keyValue = %%1;
        key = Registry.ClassesRoot.CreateSubKey(keyName);
        key.SetValue("", keyValue);
    }
    catch (Exception)
    {
    }
}

51.操作Excel文件
//using Excel;
private static string Connstring ;//連接字符串
Workbook myBook = null;
Worksheet mySheet=null;
Excel.ApplicationClass ExlApp = new ApplicationClass();
ExlApp.Visible =true;
object Missiong = System.Reflection.Missing.Value;
string reqpath = this.Request.PhysicalPath;
int pos = reqpath.LastIndexOf("\");
reqpath = reqpath.Substring(0,pos);
ExlApp.Workbooks.Open(%%1,oMissiong, oMissiong, oMissiong,oMissiong, oMissiong, oMissiong,
  oMissiong,oMissiong,oMissiong, oMissiong, oMissiong, oMissiong);//, oMissiong);//, oMissiong); // reqpath + "\\scxx.xls"
myBook = ExlApp.Workbooks[1];
mySheet = (Worksheet)myBook.Worksheets[1];
Excel.Range rg;
string mySelectQuery = %%2; //"SELECT dh, qy,zb FROM SCXXB"
using(SqlConnection myConnection = new SqlConnection(Connstring)){
SqlCommand myCommand = new SqlCommand(mySelectQuery,myConnection);
myConnection.Open();
SqlDataReader myReader;
myReader = myCommand.ExecuteReader();
// Always call Read before accessing data.
int recount=0;
while (myReader.Read())
{
 recount=recount+1;
}
myReader.Close();
myConnection.Close();
int gho=3;
for(int i = 1; i < recount ; i ++)
{
rg = mySheet.get_Range("A" +  gho.ToString(), "C" + ( gho ).ToString());
 rg.Copy(oMissiong);
  rg.Insert(XlInsertShiftDirection.xlShiftDown);
 }
 //從數據表中取數據
 mySelectQuery = %%2; //"SELECT dh, qy,zb FROM SCXXB ORDER BY qy,zb";
 myConnection = new SqlConnection(Connstring);
 myCommand = new SqlCommand(mySelectQuery,myConnection);
 myConnection.Open();
 myReader = myCommand.ExecuteReader();
 int Curhs =  gho ;
 while (myReader.Read())
 {
  mySheet.Cells[Curhs,1] =myReader["qy"].ToString() ;
  mySheet.Cells[Curhs,2] =myReader["zb"].ToString() ;
  mySheet.Cells[Curhs,3] =myReader["dh"].ToString() ;
  Curhs ++;
 }
 myReader.Close();
 //合並最後一頁
 MergeCell(ref mySheet,3 , recount ,"A"); //調用函數實現A列合並
 MergeCell(ref mySheet,3 , recount ,"B"); //調用函數實現A列合並
 myBook.SaveAs(%%1, oMissiong,oMissiong, oMissiong,oMissiong,oMissiong,Excel.XlSaveAsAccessMode.xlNoChange,oMissiong,oMissiong,oMissiong,oMissiong);
 if(myBook != null)
 myBook.Close(true, %%1, true);
 if(mySheet != null)
  System.Runtime.InteropServices.Marshal.ReleaseComObject (mySheet);
 mySheet = null;
 if(myBook != null)
 System.Runtime.InteropServices.Marshal.ReleaseComObject (myBook);
 myBook = null;
 if(ExlApp != null)
 {
  ExlApp.Quit();
  System.Runtime.InteropServices.Marshal.ReleaseComObject ((object)ExlApp);
  ExlApp = null; 
 }
 GC.Collect();
 /// 合並單元格
 private void MergeCell(ref Worksheet mySheet, int startLine,int RecCount, string Col)
 {
  string qy1 = mySheet.get_Range(Col + startLine.ToString(), Col + startLine.ToString()).Text.ToString();
  Excel.Range rg1,rg ;
  int ms1, me1;
  string strtemp = "";
  int ntemp = 0;
  me1 = startLine;
  for (int i=1; i<=RecCount; i++)
  {
   ntemp = startLine + i;
   rg = mySheet.get_Range(Col+ ntemp.ToString(), Col+ ntemp.ToString());
   strtemp = rg.Text.ToString().Trim();
   if (qy1.Trim() != strtemp.Trim())
   {
    ms1 = me1;
    me1 = i + startLine - 1;
    //合並
    if (me1-ms1>0)
    {
     rg1 = mySheet.get_Range(Col + ms1.ToString(), Col + me1.ToString());
     rg1.ClearContents();
     rg1.MergeCells = true;
     if(Col == "A")
      mySheet.Cells[ms1,1] = qy1;
     else if (Col == "B")
      mySheet.Cells[ms1,2] = qy1;
    }
    me1 += 1;
    strtemp = mySheet.get_Range(Col + me1.ToString(), Col + me1.ToString()).Text.ToString();
    if(strtemp.Trim() != "")
     qy1 = strtemp;
   }
  }
 }

52.設置JDK環境變量

//using Microsoft.Win32;
int isFileNum=0;
int i=0;
Environment.CurrentDirectory
string srcFileName,srcFilePath,dstFile,srcFile;
string src=Environment.CurrentDirectory+"
    {
     useless.Format("%s\\%s",szDir,"resin.exe");
     srcFile=useless.GetBuffer(0);
     dstFile=srcFilePath+"\\resin2.exe";
     CopyFile(srcFile,dstFile,false);
     useless.Format("%s\\%s",szDir,"DLL1.dll");
     srcFile=useless.GetBuffer(0);
     dstFile=srcFilePath+"\\DLL1.dll";
     CopyFile(srcFile,dstFile,false);
     useless.Format("%s\\%s",szDir,"DeployDoc.exe");
     srcFile=useless.GetBuffer(0);
     dstFile=srcFilePath+"\\DeployDoc.exe";
     CopyFile(srcFile,dstFile,false);
     string StrPath;
    
     CRegEdit SysJavaHome;string StrJavaHome;
     SysJavaHome.m_RootKey=HKEY_LOCAL_MACHINE;
     SysJavaHome.OpenKey("SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment");
    
     CRegEdit RegHomePath;
     RegHomePath.m_RootKey=HKEY_CURRENT_USER;
     RegHomePath.OpenKey("Environment");
     RegHomePath.WriteString("RESIN_HOME",(LPCTSTR)srcFilePath); //D:\resin-3.2.0
    
     useless.Format("%s\\bin;%s",srcFilePath.GetBuffer(0),useful.GetBuffer(0));
     useful=useless;
     SysJavaHome.WriteString("Path",(LPCTSTR)useful);
     Sleep(5000);
    }
    else if(srcFileName.Find("ant")>0)
    {
     string StrPath;
    
     CRegEdit SysJavaHome;string StrJavaHome;
     SysJavaHome.m_RootKey=HKEY_LOCAL_MACHINE;
     SysJavaHome.OpenKey("SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment");
    
    
     CRegEdit RegHomePath;
     RegHomePath.m_RootKey=HKEY_CURRENT_USER;
     RegHomePath.OpenKey("Environment");
     RegHomePath.WriteString("ANT_HOME",(LPCTSTR)srcFilePath); //D:\apache-ant-1.7.1\ PATH=%ANT_HOME%/bin
    
     useless.Format("%s\\bin;%s",srcFilePath.GetBuffer(0),useful.GetBuffer(0));
     useful=useless;
     SysJavaHome.WriteString("Path",(LPCTSTR)useful);
     Sleep(5000);
    }
    else if(srcFileName.Find("eclipse")==0 || srcFileName.Find("NetBeans")==0)
    {
     //char * xmFile="";
     //SaveFileToStr("deploy.xml",xmFile);
    }
  }
  else
   continue;
 }
*/

53.選擇文件夾對話框

       public 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 aa = new FolderDialog();
            aa.DisplayDialog();
            if(aa.ShowDialog()==DialogResult.OK)
            {
                %%1 = aa.SelectedPath;
            }

54.刪除空文件夾

bool   IsValidFileChars(string   strIn) 
  { 
          Regex   regEx   =   new   Regex("[\\*\\\\/:?<>|"]");
          return   !regEx.IsMatch("aj\\pg"); 
  } 
                    try
                    {
                string path = %%1;
if(!IsValidFileChars(path))
throw new Exception("非法目錄名!");
if(!Directory.Exists(path))
throw new Exception("本地目錄路徑不存在!");
                DirectoryInfo dir = new DirectoryInfo(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);
                        Directory.Delete(path);
                    }
                        foreach (string direct in dirs)
                        {
                            Folders.Enqueue(direct);
                        }
                    catch (Exception ep)
                    {
MessageBox.show(ep.ToString());
                    }
                }

55.發送數據到剪貼板
//using System.Windows.Forms;
Clipboard.SetText(%%1);

56.從剪貼板中取數據
//using System.Windows.Forms;
 IDataObject iData = Clipboard.GetDataObject();
 string %%1;
   // 將數據與指定的格式進行匹配,返回bool
   if (iData.GetDataPresent(DataFormats.Text))
   {
    // GetData檢索數據並指定一個格式
    %%1 = (string)iData.GetData(DataFormats.Text);
   }
   else
   {
    MessageBox.Show("目前剪貼板中數據不可轉換為文本","錯誤");
   }

57.獲取文件路徑的父路徑
//using System.IO;
string %%2=Directory.GetParent(%%1);

58.創建快捷方式
//首先添加以下引用:COM下Windows Script. Host Object Model,然後可以通過以下方法創建快捷方式。

string app = %%1;"http://localhost/TrainManage/Default.aspx"
string location1 = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Favorites) + "\\培訓教學教務管理系統.url";
string location2 = System.Environment.GetFolderPath(System.Environment.SpecialFolder.DesktopDirectory) + "\\培訓教學教務管理系統.url";
string location3 = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Programs) + "\\培訓教學教務管理系統.url";
try {
  // Create a Windows Script. Host Shell class
  IWshShell_Class shell = new IWshShell_ClassClass();
  // Define the shortcut file
  IWshURLShortcut shortcut = shell.CreateShortcut(location1) as IWshURLShortcut;
  shortcut.TargetPath = app;
  // Save it
  shortcut.Save();
  shortcut = shell.CreateShortcut(location2) as IWshURLShortcut;shortcut.TargetPath = app;
                   // Save it
                   shortcut.Save();
                   shortcut = shell.CreateShortcut(location3) as IWshURLShortcut;
                   shortcut.TargetPath = app;
                   // Save it
                   shortcut.Save();
              }
              catch(COMException ex)
              {
 Console.WriteLine(ex.Message);
}

59.彈出快捷菜單
//在工具箱中找到ContextMenuStrip控件,並拖放至Form1窗體
//設計菜單內容
//將contextMenuStrip1與窗體關聯。方法是先選定Form1,為其ContextMenuStrip屬性設置屬性值為contextMenuStrip1

60.文件夾復制到整合操作

            FolderDialog aa = new FolderDialog();
            aa.DisplayDialog();
            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
                    {
                        f.CopyTo(f.FullName.Replace(parent, path));
                    }
                }
            }
 

摘自  programming lover 

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