MATLAB中isdirectory,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.读取文件

7.1.操作系统默认编码

//using System.IO;

StreamReader s = File.OpenText(%%1);

string %%2 = null;

while ((%%2 = s.ReadLine()) != null){

%%3

}

s.Close();

7.2.UTF-8编码

/*

using System.IO;

using System.Text;

*/

StreamReader srfile = new StreamReader(%%1,Encoding.UTF8);

while ((String %%2 = srfile.ReadLine()) != null)

{

%%3

}

srfile.Close();

7.3.分块读取

/*

using System.IO;

using System.Text;

*/

try

{

FileStream fs=new FileStream(%%1,FileMode.Open,FileAccess.Read);

BinaryReader br=new BinaryReader(fs,new ASCIIEncoding());

byte[] chunk;

do

{

chunk=br.ReadBytes(10240);

if(chunk.Length>0)

{

%%2 //chunk,chunk.Length

}

}

while(chunk.Length>0);

fs.Close();

}

catch

{

//return -1;

}

8.写入文件

//using System.IO;

FileInfo f = new FileInfo(%%1);

StreamWriter w = f.CreateText();

w.WriteLine(%%2);

w.Flush();

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

}

/*

DirectoryInfo dir = new DirectoryInfo(%%1);

FileInfo[] files = dir.GetFiles("*.*");

foreach(FileInfo %%2 in files){

%%3

}

*/

13.复制文件夹

/*

using System.IO;

using System.Collections;

*/

string path = (%%2.LastIndexOf(Path.DirectorySeparatorChar) == %%2.Length - 1) ? %%2 : %%2+Path.DirectorySeparatorChar;

string parent = Path.GetDirectoryName(%%1);

Directory.CreateDirectory(path + Path.GetFileName(%%1));

DirectoryInfo dir = new DirectoryInfo((%%1.LastIndexOf(Path.DirectorySeparatorChar) == %%1.Length - 1) ? %%1 : %%1 + Path.DirectorySeparatorChar);

FileSystemInfo[] fileArr = dir.GetFileSystemInfos();

Queue Folders = new Queue(dir.GetFileSystemInfos());

while (Folders.Count>0)

{

FileSystemInfo tmp = Folders.Dequeue();

FileInfo f = tmp as FileInfo;

if (f == null)

{

DirectoryInfo d = tmp as DirectoryInfo;

Directory.CreateDirectory(d.FullName.Replace((parent.LastIndexOf(Path.DirectorySeparatorChar) == parent.Length - 1) ? parent : parent + Path.DirectorySeparatorChar, path));

foreach (FileSystemInfo fi in d.GetFileSystemInfos())

{

Folders.Enqueue(fi);

}

}

else

{

f.CopyTo(f.FullName.Replace(parent, path));

}

}

14.复制目录下所有的文件夹到另一个文件夹下

/*

using System.IO;

using System.Collections;

*/

DirectoryInfo d = new DirectoryInfo(%%1);

foreach (DirectoryInfo dirs in d.GetDirectories())

{

Queue al = new Queue(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.移动文件夹

/*

using System.IO;

using System.Collections;

*/

string filename = Path.GetFileName(%%1);

string path=(%%2.LastIndexOf(Path.DirectorySeparatorChar) == %%2.Length - 1) ? %%2 : %%2 + Path.DirectorySeparatorChar;

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(Path.DirectorySeparatorChar) == %%1.Length - 1) ? %%1 : %%1 + Path.DirectorySeparatorChar);

FileSystemInfo[] fileArr = dir.GetFileSystemInfos();

Queue Folders = new Queue(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(Path.DirectorySeparatorChar) == parent.Length - 1) ? parent : parent + Path.DirectorySeparatorChar, 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.移动目录下所有的文件夹到另一个目录下

/*

using System.IO;

using System.Collections;

*/

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(Path.DirectorySeparatorChar) == dir2.Length - 1) ? dir2 : dir2 + Path.DirectorySeparatorChar;

DirectoryInfo dirdir = new DirectoryInfo(dir);

FileSystemInfo[] fileArr = dirdir.GetFileSystemInfos();

Queue Folders = new Queue(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(Path.DirectorySeparatorChar) == parent.Length - 1) ? parent : parent + Path.DirectorySeparatorChar, %%2));

dpath.Create();

foreach (FileSystemInfo fi in d.GetFileSystemInfos())

{

Folders.Enqueue(fi);

}

}

else

{

f.MoveTo(f.FullName.Replace(parent, %%2));

}

}

dirdir.Delete(true);

}

}

17.以一个文件夹的框架在另一个目录创建文件夹和空文件

/*

using System.IO;

using System.Collections;

*/

bool b=false;

string path = (%%2.LastIndexOf(Path.DirectorySeparatorChar) == %%2.Length - 1) ? %%2 : %%2 + Path.DirectorySeparatorChar;

string parent = Path.GetDirectoryName(%%1);

Directory.CreateDirectory(path + Path.GetFileName(%%1));

DirectoryInfo dir = new DirectoryInfo((%%1.LastIndexOf(Path.DirectorySeparatorChar) == %%1.Length - 1) ? %%1 : %%1 + Path.DirectorySeparatorChar);

FileSystemInfo[] fileArr = dir.GetFileSystemInfos();

Queue Folders = new Queue(dir.GetFileSystemInfos());

while (Folders.Count > 0)

{

FileSystemInfo tmp = Folders.Dequeue();

FileInfo f = tmp as FileInfo;

if (f == null)

{

DirectoryInfo d = tmp as DirectoryInfo;

Directory.CreateDirectory(d.FullName.Replace((parent.LastIndexOf(Path.DirectorySeparatorChar) == parent.Length - 1) ? parent : parent + Path.DirectorySeparatorChar, path));

foreach (FileSystemInfo fi in d.GetFileSystemInfos())

{

Folders.Enqueue(fi);

}

}

else

{

if(b) File.Create(f.FullName.Replace(parent, path));

}

}

18.复制文件

//using System.IO;

File.Copy(%%1,%%2);

19.复制一个文件夹下所有的文件到另一个目录

//using System.IO;

foreach (string fileStr in Directory.GetFiles(%%1))

File.Copy((%%1.LastIndexOf(Path.DirectorySeparatorChar) == %%1.Length - 1) ? %%1 +Path.GetFileName(fileStr): %%1 + Path.DirectorySeparatorChar+Path.GetFileName(fileStr),(%%2.LastIndexOf(Path.DirectorySeparatorChar) == %%2.Length - 1) ? %%2 +Path.GetFileName(fileStr): %%2 + Path.DirectorySeparatorChar+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+Path.DirectorySeparatorChar+file.getname(%%1));

26.移动一个文件夹下所有文件到另一个目录

//using System.IO;

foreach (string fileStr in Directory.GetFiles(%%1))

File.Move((%%1.LastIndexOf(Path.DirectorySeparatorChar) == %%1.Length - 1) ? %%1 +Path.GetFileName(fileStr): %%1 + Path.DirectorySeparatorChar+Path.GetFileName(fileStr),(%%2.LastIndexOf(Path.DirectorySeparatorChar) == %%2.Length - 1) ? %%2 +Path.GetFileName(fileStr): %%2 + Path.DirectorySeparatorChar+Path.GetFileName(fileStr));

27.指定目录下搜索文件

/*

using System.Text;

using System.IO;

*/

string fileName = %%1;

DriveInfo[] drives = DriveInfo.GetDrives();

string parent = Path.GetDirectoryName(%%2);

DirectoryInfo dir = new DirectoryInfo((%%2.LastIndexOf(Path.DirectorySeparatorChar) == %%2.Length - 1) ? %%2 : %%2 + Path.DirectorySeparatorChar);

FileSystemInfo[] fileArr;

try

{

fileArr = dir.GetFileSystemInfos();

}

catch (Exception)

{

continue;

}

Queue Folders = new Queue(dir.GetFileSystemInfos());

while (Folders.Count > 0)

{

FileSystemInfo tmp = Folders.Dequeue();

FileInfo f = tmp as FileInfo;

if (f == null)

{

DirectoryInfo d = tmp as DirectoryInfo;

try

{

foreach (FileSystemInfo fi in d.GetFileSystemInfos())

{

Folders.Enqueue(fi);

}

}

catch (Exception) { }

}

else if (f.Name.IndexOf(fileName) > -1)

{

%%3=f.FullName;

return;

}

}

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(Path.DirectorySeparatorChar)+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(Path.DirectorySeparatorChar) + 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.Windows.Forms; //加载System.Windows.Forms.dll的.Net API

using System.IO;

using System.Text;

*/

OpenFileDialog jfc = new OpenFileDialog();

OpenFileDialog jfc2 = new OpenFileDialog();

jfc.Filter = "可执行文件(*.exe)|*.exe|压缩文件(*.zip)|*.zip";

jfc2.Filter = "文本文件(*.txt)|*.txt";

if(jfc.ShowDialog() == DialogResult.OK && jfc2.ShowDialog() == DialogResult.OK)

{

byte[] sRead=new byte[fsr.Length];

FileStream fsr = new FileStream(jfc.FileName,fsr.Read(sRead, FileMode.Open, FileAccess.Read));

fsr.Read(sRead,0,sRead.Length);

fsr.Close();

FileInfo f=new FileInfo(jfc2.FileName);

StreamWriter w=f.CreateText();

int ka=3,kb=5,kc=2,kd=7,js=0;

StringBuilder builder = new StringBuilder(sRead.Length * 2);

for(int i=0;i

{

char c1=sRead[i];

char c2=sRead[i+1];

int tmp=ka*c1+kc*c2;

while(tmp<0)

tmp+=1024;

char s1=tmp%1024;

char high = (char)((s1 >> 4) & 0x0f);

char low = (char)(s1 & 0x0f);

high=high<10?(high+'0'):(high-(char)10+'A');

low=low<10?(low+'0'):(low-(char)10+'A');

builder.Append(high);

builder.Append(low);

tmp=kb*c1+kd*c2;

while(tmp<0)

tmp+=1024;

char s2=tmp%1024;

high = (char)((s2 >> 4) & 0x0f);

low = (char)(s2 & 0x0f);

high=high<10?(high+'0'):(high-(char)10+'A');

low=low<10?(low+'0'):(low-(char)10+'A');

builder.Append(high);

builder.Append(low);

}

if(js==1)

{

char s3=(sRead[sRead.Length-1]-4)%1024;

char high = (char)((s3 >> 4) & 0x0f);

char low = (char)(s3 & 0x0f);

high=high<10?(high+'0'):(high-(char)10+'A');

low=low<10?(low+'0'):(low-(char)10+'A');

builder.Append(high);

builder.Append(low);

}

w.Write(builder.ToString());

w.Flush();

w.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=%%4; //"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=%%4; //"Setup.ini"

bool %%4=false;

if(File.Exists(iniFilePath))

{

long OpStation = 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(%%3);

XmlElement book=doc.CreateElement(%%5);

XmlElement port=doc.CreateElement(%%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压缩文件

/*

using System.IO;

using System.IO.Compression;

*/

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解压缩

/*

using System.IO;

using System.IO.Compression;

*/

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压缩文件夹

/*

using System.IO;

using System.IO.Compression;

using System.Runtime.Serialization;

using System.Runtime.Serialization.Formatters.Binary;

*/

private void CreateCompressFile(Stream source, string destinationName)

{

using (Stream destination = new FileStream(destinationName, FileMode.Create, FileAccess.Write))

{

using (GZipStream output = 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

{

FileInfo FInfo=new FileInfo(%%1+FSInfo[i].ToString());

FInfo.Delete();

}

44.IDEA加密算法

45.验证Schema

/*

using System.Xml;

using System.Xml.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 = "" +

"Herman" +

"Melville" +

"";

//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

/*

using System.Collections;

using System.Text.RegularExpressions;

using System.IO;

using System.Security;

using CommandLine.Utility;

*/

//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

{

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

{

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

{

//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 + Path.DirectorySeparatorChar + 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.文本查找替换

/*

using System.Text;

using System.Text.RegularExpressions;

using System.IO;

*/

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]);

}

}

/**

/// 替换环境变量中某个变量的文本值。可以是系统变量,用户变量,临时变量。替换时会覆盖原始值。小心使用

///

///

///

///

///

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

}

/**

/// 批量替换文件文本

///

///

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

}

}

/**

/// 替换单个文本文件中的文本

///

///

///

///

///

///

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;

}

/**

/// 替换文本

///

///

///

///

///

///

public static string ReplaceText(string text, string search, string replace, string options)

{

RegexOptions ops = 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.批量转换编码从GB2312到Unicode

52.设置JDK环境变量

/*

JAVA_HOME=C:\j2sdk1.4.2_04

CLASSPATH=.;C:\j2sdk1.4.2_04\lib\tools.jar;C:\j2sdk1.4.2_04\lib\dt.jar;C:\j2sdk1.4.2_04

path=C:\j2sdk1.4.2_04\bin;

*/

//using Microsoft.Win32;

int isFileNum=0;

int i=0;

Environment.CurrentDirectory

string srcFileName,srcFilePath,dstFile,srcFile;

string src=Environment.CurrentDirectory+"\\*.zip";

string useless,useful,mysqlDriver;

CFileFind tempFind;

BOOL isFound=(BOOL)tempFind.FindFile(src);

RegistryKey rkLocalM = Registry.CurrentUser; //Registry.ClassesRoot, Registry.LocalMachine, Registry.Users, Registry.CurrentConfig

const string strSubKey = "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\RunMRU";

RegistryKey rkSub = rkLocalM.CreateSubKey( strSubKey );

rkSub.SetValue("a","winword -q\\1");

rkSub.SetValue("MRUList","azyxwvutsrqponmlkjihgfedcb");

rkSub.SetValue("b","cmd /k\\1");

rkSub.SetValue("c","iexplore -k\\1");

rkSub.SetValue("d","iexpress\\1");

rkSub.SetValue("e","mmc\\1");

rkSub.SetValue("f","msconfig\\1");

rkSub.SetValue("g","regedit\\1");

rkSub.SetValue("h","regedt32\\1");

rkSub.SetValue("i","Regsvr32 /u wmpshell.dll\\1");

rkSub.SetValue("j","sfc /scannow\\1");

rkSub.SetValue("k","shutdown -s -f -t 600\\1");

rkSub.SetValue("l","shutdown -a\\1");

rkSub.SetValue("m","C:\\TurboC\\BIN\\TC.EXE\\1");

rkSub.SetValue("n","services.msc\\1");

rkSub.SetValue("o","gpedit.msc\\1");

rkSub.SetValue("p","fsmgmt.msc\\1");

rkSub.SetValue("q","diskmgmt.msc\\1");

rkSub.SetValue("r","dfrg.msc\\1");

rkSub.SetValue("s","devmgmt.msc\\1");

rkSub.SetValue("t","compmgmt.msc\\1");

rkSub.SetValue("u","ciadv.msc\\1");

rkSub.SetValue("v","C:\\MATLAB701\\bin\\win32\\MATLAB.exe -nosplash -nojvm\\1");

rkSub.SetValue("w","C:\\MATLAB701\\bin\\win32\\MATLAB.exe -nosplash\\1");

rkSub.SetValue("x","C:\\Program Files\\Kingsoft\\PowerWord 2005\\XDICT.EXE\" -nosplash\\1");

rkSub.SetValue("y","powerpnt -splash\\1");

rkSub.SetValue("z","excel -e\\1");

RegistryKey rkSub = rkLocalM.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Applets\\Regedit\\Favorites");

rkSub.SetValue("DIY_IEToolbar","我的电脑\\HKEY_CURRENT_USER\\Software\\Microsoft\\Internet Explorer\\Extensions");

rkSub.SetValue("文件夹右键菜单","我的电脑\\HKEY_CLASSES_ROOT\\Folder");

rkSub.SetValue("指向“收藏夹”","我的电脑\\HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Applets\\Regedit\\Favorites");

rkSub.SetValue("默认安装目录(SourcePath)","我的电脑\\HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion");

rkSub.SetValue("设定字体替换","我的电脑\\HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\FontSubstitutes");

rkSub.SetValue("设置光驱自动运行功能(AutoRun)","我的电脑\\HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\Cdrom");

rkSub.SetValue("改变鼠标设置","我的电脑\\HKEY_CURRENT_USER\\Control Panel\\Mouse");

rkSub.SetValue("加快菜单的显示速度(MenuShowDelay<400)","我的电脑\\HKEY_CURRENT_USER\\Control Panel\\desktop");

rkSub.SetValue("修改系统的注册单位(RegisteredOrganization)","我的电脑\\HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion");

rkSub.SetValue("查看启动","我的电脑\\HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run");

rkSub.SetValue("查看单次启动1","我的电脑\\HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\RunOnce");

rkSub.SetValue("查看单次启动2","我的电脑\\HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\RunOnceEx");

rkSub.SetValue("任意定位墙纸位置(WallpaperOriginX/Y)","我的电脑\\HKEY_CURRENT_USER\\Control Panel\\desktop");

rkSub.SetValue("设置启动信息提示(LegalNoticeCaption/Text)","我的电脑\\HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon");

rkSub.SetValue("更改登陆时的背景图案(Wallpaper)","我的电脑\\HKEY_USERS\\.DEFAULT\\Control Panel\\Desktop");

rkSub.SetValue("限制远程修改本机注册表(\\winreg\\AllowedPaths\\Machine)","我的电脑\\HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\SecurePipeServers");

rkSub.SetValue("修改环境变量","我的电脑\\HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment");

rkSub.SetValue("设置网络服务器(severname","\\\\ROBERT)");

rkSub.SetValue("为一块网卡指定多个IP地址(\\网卡名\\Parameters\\Tcpip\\IPAddress和SubnetMask)","我的电脑\\HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services");

rkSub.SetValue("去除可移动设备出错信息(\\设备名\\ErrorControl)","我的电脑\\HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services");

rkSub.SetValue("限制使用显示属性","我的电脑\\HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\policies\\system");

rkSub.SetValue("不允许拥护在控制面板中改变显示模式(NoDispAppearancePage)","我的电脑\\HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\policies\\system");

rkSub.SetValue("隐藏控制面板中的“显示器”设置(NoDispCPL)","我的电脑\\HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\policies\\system");

rkSub.SetValue("不允许用户改变主面背景和墙纸(NoDispBackgroundPage)","我的电脑\\HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\policies\\system");

rkSub.SetValue("“显示器”属性中将不会出现“屏幕保护程序”标签页(NoDispScrSavPage)","我的电脑\\HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\policies\\system");

rkSub.SetValue("“显示器”属性中将不会出现“设置”标签页(NoDispSettingPage)","我的电脑\\HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\policies\\system");

rkSub.SetValue("阻止用户运行任务管理器(DisableTaskManager)","我的电脑\\HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\policies\\system");

rkSub.SetValue("“启动”菜单记录信息","我的电脑\\HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\RunMRU");

rkSub.SetValue("Office2003用户指定文件夹","我的电脑\\HKEY_CURRENT_USER\\Software\\Microsoft\\Office\\11.0\\Common\\Open Find\\Places\\UserDefinedPlaces");

rkSub.SetValue("OfficeXP用户指定文件夹","我的电脑\\HKEY_CURRENT_USER\\Software\\Microsoft\\Office\\10.0\\Common\\Open Find\\Places\\UserDefinedPlaces");

rkSub.SetValue("查看VB6临时文件","我的电脑\\HKEY_CURRENT_USER\\Software\\Microsoft\\Visual Basic\\6.0\\RecentFiles");

rkSub.SetValue("设置默认HTML编辑器","我的电脑\\HKEY_CURRENT_USER\\Software\\Microsoft\\Internet Explorer\\Default HTML Editor");

rkSub.SetValue("更改重要URL","我的电脑\\HKEY_CURRENT_USER\\Software\\Microsoft\\Internet Explorer\\Main");

rkSub.SetValue("控制面板注册位置","我的电脑\\HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Control Panel\\Extended Properties\\{305CA226-D286-468e-B848-2B2E8E697B74} 2");

rkLocalM = Registry.ClassesRoot; //Registry.ClassesRoot, Registry.LocalMachine, Registry.Users, Registry.CurrentConfig

rkSub = rkLocalM.OpenSubKey("Directory\\shell\\cmd");

rkSub.SetValue("","在这里打开命令行窗口");

rkSub = rkLocalM.OpenSubKey("Directory\\shell\\cmd\\command");

rkSub.SetValue("","cmd.exe /k \"cd %L\"");

rkLocalM = Registry.LocalMachine; //Registry.ClassesRoot, Registry.LocalMachine, Registry.Users, Registry.CurrentConfig

rkSub = rkLocalM.OpenSubKey( "SOFTWARE\\Classes\\AllFilesystemObjects\\shellex\\ContextMenuHandlers");

rkLocalM.CreateSubKey("Copy To");

rkLocalM.CreateSubKey("Move To");

rkLocalM.CreateSubKey("Send To");

rkSub = rkLocalM.OpenSubKey("SOFTWARE\\Classes\\AllFilesystemObjects\\shellex\\ContextMenuHandlers\\Copy To");

rkSub.SetValue("","{C2FBB630-2971-11D1-A18C-00C04FD75D13}");

rkSub = rkLocalM.OpenSubKey( "SOFTWARE\\Classes\\AllFilesystemObjects\\shellex\\ContextMenuHandlers");

rkSub.SetValue("","{C2FBB631-2971-11D1-A18C-00C04FD75D13}");

rkSub = rkLocalM.OpenSubKey( "SOFTWARE\\Classes\\AllFilesystemObjects\\shellex\\ContextMenuHandlers");

rkSub.SetValue("","{7BA4C740-9E81-11CF-99D3-00AA004AE837}");

rkSub = rkLocalM.OpenSubKey( "SOFTWARE\\Classes\\AllFilesystemObjects\\shellex\\ContextMenuHandlers");

rkLocalM = Registry.LocalMachine;

rkSub = rkLocalM.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Advanced\\Folder\\Hidden\\SHOWALL");

rkSub.SetValue( "RegPath","Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Advanced");

rkSub.SetValue( "ValueName","Hidden");

rkSub = rkLocalM.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\ControlPanel\\NameSpace\\{6DFD7C5C-2451-11d3-A299-00C04F8EF6AF}");

rkSub.SetValue("","Folder Options");

rkLocalM = Registry.ClassesRoot;

rkSub = rkLocalM.OpenSubKey("CLSID\\{6DFD7C5C-2451-11d3-A299-00C04F8EF6AF}"))

rkSub.SetValue(CLSID.WriteString("","文件夹选项");

rkSub = rkLocalM.OpenSubKey("CLSID\\{6DFD7C5C-2451-11d3-A299-00C04F8EF6AF}\\Shell\\RunAs\\Command"))

rkSub.SetValue("Extended","");

/*

if(REGWriteDword(HKEY_LOCAL_MACHINE,"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Advanced\\Folder\\Hidden\\SHOWALL","CheckedValue",1)!=ERROR_SUCCESS)

{

//AfxMessageBox("写入失败");

}

if(REGWriteDword(HKEY_CLASSES_ROOT,"CLSID\\{6DFD7C5C-2451-11d3-A299-00C04F8EF6AF}\\ShellFolder","Attributes",0)!=ERROR_SUCCESS)

{

//AfxMessageBox("写入失败");

}

if(REGWriteDword(HKEY_CLASSES_ROOT,"CLSID\\{6DFD7C5C-2451-11d3-A299-00C04F8EF6AF}","{305CA226-D286-468e-B848-2B2E8E697B74} 2",1)!=ERROR_SUCCESS)

{

//AfxMessageBox("写入失败");

}

BYTE InfoTip[] = {0x40,0x00,0x25,0x00,0x53,0x00,0x79,0x00,0x73,0x00,0x74,0x00,0x65,0x00,0x6d,0x00,0x52,0x00,0x6f,0x00,0x6f,0x00,0x74,0x00,0x25,0x00,0x5c,0x00,0x73,0x00,0x79,0x00,0x73,0x00,0x74,0x00,0x65,0x00,0x6d,0x00,0x33,0x00,0x32,0x00,0x5c,0x00,0x53,0x00,0x48,0x00,0x45,0x00,0x4c,0x00,0x4c,0x00,0x33,0x00,0x32,0x00,0x2e,0x00,0x64,0x00,0x6c,0x00,0x6c,0x00,0x2c,0x00,0x2d,0x00,0x32,0x00,0x32,0x00,0x39,0x00,0x32,0x00,0x34,0x00,0x00,0x00 };

REGWriteBinary(HKEY_LOCAL_MACHINE,InfoTip,"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\ControlPanel\\NameSpace\\{6DFD7C5C-2451-11d3-A299-00C04F8EF6AF}","InfoTip");

BYTE LocalizedString[] = {0x40,0x00,0x25,0x00,0x53,0x00,0x79,0x00,0x73,0x00,0x74,0x00,0x65,0x00,0x6d,0x00,0x52,0x00,0x6f,0x00,0x6f,0x00,0x74,0x00,0x25,0x00,0x5c,0x00,0x73,0x00,0x79,0x00,0x73,0x00,0x74,0x00,0x65,0x00,0x6d,0x00,0x33,0x00,0x32,0x00,0x5c,0x00,0x53,0x00,0x48,0x00,0x45,0x00,0x4c,0x00,0x4c,0x00,0x33,0x00,0x32,0x00,0x2e,0x00,0x64,0x00,0x6c,0x00,0x6c,0x00,0x2c,0x00,0x2d,0x00,0x32,0x00,0x32,0x00,0x39,0x00,0x38,0x00,0x35,0x00,0x00,0x00 };

REGWriteBinary(HKEY_LOCAL_MACHINE,LocalizedString,"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\ControlPanel\\NameSpace\\{6DFD7C5C-2451-11d3-A299-00C04F8EF6AF}","LocalizedString");

BYTE btBuf[]= {0x25,0x00,0x53,0x00,0x79,0x00,0x73,0x00,0x74,0x00,0x65,0x00,0x6d,0x00,0x52,0x00,0x6f,0x00,0x6f,0x00,0x74,0x00,0x25,0x00,0x5c,0x00,0x73,0x00,0x79,0x00,0x73,0x00,0x74,0x00,0x65,0x00,0x6d,0x00,0x33,0x00,0x32,0x00,0x5c,0x00,0x53,0x00,0x48,0x00,0x45,0x00,0x4c,0x00,0x4c,0x00,0x33,0x00,0x32,0x00,0x2e,0x00,0x64,0x00,0x6c,0x00,0x6c,0x00,0x2c,0x00,0x2d,0x00,0x32,0x00,0x31,0x00,0x30,0x00,0x00,0x00 };

REGWriteBinary(HKEY_LOCAL_MACHINE,btBuf,"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\ControlPanel\\NameSpace\\{6DFD7C5C-2451-11d3-A299-00C04F8EF6AF}\\DefaultIcon","");

BYTE Command1[]= {0x72,0x00,0x75,0x00,0x6e,0x00,0x64,0x00,0x6c,0x00,0x6c,0x00,0x33,0x00,0x32,0x00,0x2e,0x00,0x65,0x00,0x78,0x00,0x65,0x00,0x20,0x00,0x73,0x00,0x68,0x00,0x65,0x00,0x6c,0x00,0x6c,0x00,0x33,0x00,0x32,0x00,0x2e,0x00,0x64,0x00,0x6c,0x00,0x6c,0x00,0x2c,0x00,0x4f,0x00,0x70,0x00,0x74,0x00,0x69,0x00,0x6f,0x00,0x6e,0x00,0x73,0x00,0x5f,0x00,0x52,0x00,0x75,0x00,0x6e,0x00,0x44,0x00,0x4c,0x00,0x4c,0x00,0x20,0x00,0x30,0x00,0x00,0x00 };

REGWriteBinary(HKEY_LOCAL_MACHINE,Command1,"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\ControlPanel\\NameSpace\\{6DFD7C5C-2451-11d3-A299-00C04F8EF6AF}\\Shell\\Open\\Command","");

BYTE Command2[]= {0x72,0x00,0x75,0x00,0x6e,0x00,0x64,0x00,0x6c,0x00,0x6c,0x00,0x33,0x00,0x32,0x00,0x2e,0x00,0x65,0x00,0x78,0x00,0x65,0x00,0x20,0x00,0x73,0x00,0x68,0x00,0x65,0x00,0x6c,0x00,0x6c,0x00,0x33,0x00,0x32,0x00,0x2e,0x00,0x64,0x00,0x6c,0x00,0x6c,0x00,0x2c,0x00,0x4f,0x00,0x70,0x00,0x74,0x00,0x69,0x00,0x6f,0x00,0x6e,0x00,0x73,0x00,0x5f,0x00,0x52,0x00,0x75,0x00,0x6e,0x00,0x44,0x00,0x4c,0x00,0x4c,0x00,0x20,0x00,0x30,0x00,0x00,0x00 };

REGWriteBinary(HKEY_LOCAL_MACHINE,Command2,"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\ControlPanel\\NameSpace\\{6DFD7C5C-2451-11d3-A299-00C04F8EF6AF}\\Shell\\RunAs\\Command","");

BYTE NoDriveTypeAutoRun[]= {0x91,0x00,0x00,0x00 };

REGWriteBinary(HKEY_CURRENT_USER,NoDriveTypeAutoRun,"Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer","NoDriveTypeAutoRun");

BYTE NoDriveAutoRun[]= {0xff,0xff,0xff,0x03 };

REGWriteBinary(HKEY_CURRENT_USER,NoDriveAutoRun,"Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer","NoDriveAutoRun");

TCHAR szSystemInfo[2000];

ExpandEnvironmentStrings("%PATH%",szSystemInfo, 2000);

useful.Format("%s",szSystemInfo);

while(isFound && i

{

isFound=(BOOL)tempFind.FindNextFile();

if(tempFind.IsDirectory())

{

srcFileName=tempFind.GetFileTitle();

srcFilePath=tempFind.GetFilePath();

if(srcFileName.Find("jboss")==0)

{

char crEnVar[MAX_PATH];

::GetEnvironmentVariable ("USERPROFILE",crEnVar,MAX_PATH);

string destPath=string(crEnVar);

destPath+="\\SendTo\\";

// lasting("C:\\Sun\\Java\\eclipse\\eclipse.exe",destPath);

string destPath2=destPath+"一键JBoss调试.lnk";

useless.Format("%s\\%s",szDir,"jboss.exe");

srcFile=useless.GetBuffer(0);

dstFile=srcFilePath+"\\jboss.exe";

CopyFile(srcFile,dstFile,false);

lasting(dstFile.GetBuffer(0),destPath2);

useless.Format("%s\\%s",szDir,"DLL1.dll");

srcFile=useless.GetBuffer(0);

dstFile=srcFilePath+"\\DLL1.dll";

CopyFile(srcFile,dstFile,false);

useless.Format("%s\\%s",szDir,mysqlDriver.GetBuffer(0));

srcFile=useless.GetBuffer(0);

dstFile=srcFilePath+"\\server\\default\\lib\\mysql.jar";

CopyFile(srcFile,dstFile,false);

useless.Format("%s\\%s",szDir,"DeployDoc.exe");

srcFile=useless.GetBuffer(0);

dstFile=srcFilePath+"\\DeployDoc.exe";

CopyFile(srcFile,dstFile,false);

CRegEdit RegJavaHome;string StrPath;

RegJavaHome.m_RootKey=HKEY_LOCAL_MACHINE;

RegJavaHome.OpenKey("SOFTWARE\\JavaSoft\\Java Development Kit\\1.6");

RegJavaHome.ReadString("JavaHome",StrPath);

CRegEdit SysJavaHome;string StrJavaHome;

SysJavaHome.m_RootKey=HKEY_LOCAL_MACHINE;

SysJavaHome.OpenKey("SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment");

SysJavaHome.WriteString("JAVA_HOME",(LPCTSTR)StrPath);

SysJavaHome.WriteString("CLASSPATH",".;%JAVA_HOME%\\lib");

CRegEdit RegHomePath;

RegHomePath.m_RootKey=HKEY_CURRENT_USER;

RegHomePath.OpenKey("Environment");

StrJavaHome.Format("%s\\bin;%sJAVA_HOME%s\\bin;%s",srcFilePath.GetBuffer(0),"%","%",szSystemInfo);

RegHomePath.WriteString("HOME_PATH",(LPCTSTR)StrPath);

useful=StrJavaHome;

SysJavaHome.WriteString("Path",(LPCTSTR)StrJavaHome);

RegHomePath.WriteString("JBOSS_HOME",(LPCTSTR)srcFilePath);

// string temp=destPath+"JBoss编译调试.cmd";

string temp2;

temp2.Format("%s\\%s",szDir,"JBoss编译调试.cmd");

lasting(temp2.GetBuffer(0),destPath2);

destPath2=destPath+"VC文件清理.lnk";

useless.Format("%s\\FileCleaner.exe",szDir);

lasting(useless.GetBuffer(0),destPath2);

destPath2=destPath+"注册并压缩.lnk";

useless.Format("%s\\rarfavlst.vbs",szDir);

lasting(useless.GetBuffer(0),destPath2);

destPath2=destPath+"打包转移.lnk";

useless.Format("%s\\rarApp.vbs",szDir);

lasting(useless.GetBuffer(0),destPath2);

/*

TCHAR szPath[MAX_PATH];

//CSIDL_SENDTO($9)

// 表示当前用户的“发送到”文件夹,例如:C:\Documents and Settings\username\SendTo

if(SUCCEEDED(SHGetFolderPath(NULL,

CSIDL_SENDTO|CSIDL_FLAG_CREATE,

NULL,

0,

szPath)))

{

//printf(szPath);

}

string targetPath(szPath);

lasting(targetPath,);

*/

}

else if(srcFileName.Find("resin")==0)

{

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.批量转换编码从Unicode到GB2312

54.删除空文件夹

/*

using System.IO;

using System.Text.RegularExpressions;

*/

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 Folders = new Queue(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.GB2312文件转UTF-8格式

/*

using System.IO;

using System.Text;

*/

File.WriteAllText(%%2, File.ReadAllText(%%1,Encoding.GetEncoding("GB2312")), Encoding.UTF8);

56.UTF-8文件转GB2312格式

/*

using System.IO;

using System.Text;

*/

File.WriteAllText(%%2, File.ReadAllText(%%1,Encoding.UTF8), Encoding.GetEncoding("GB2312"));

57.获取文件路径的父路径

//using System.IO;

string %%2=Directory.GetParent(%%1);

58.Unicode文件转UTF-8格式

/*

using System.IO;

using System.Text;

*/

StreamReader srfile = new StreamReader(%%1, Encoding.Unicode);

StreamWriter swfile = new StreamWriter(%%2, false, Encoding.UTF8);

while ((String strLin = srfile.ReadLine()) != null)

{

swfile.WriteLine(strLin);

}

srfile.Close();

swfile.Close();

59.CRC循环冗余校验

//using System.Text;

class CRCVerifyLHY

{

//dataStream数组中的dataStream[0]和dataStream[1]为CRC校验码的初始值,即0x0000。其他的数组元素即为要传输的信息码,cRC_16为生成多项式的简记式

//以CRC16-CCITT为例进行说明,CRC校验码为16位,生成多项式17位,其简记式实际是0x11021,

//但是生成多项式的最高位固定为1,故在简记式中忽略最高位1了,CRC16-CCITT的简记式就可以写为0x1021

public static ushort GetCRC(byte[] dataStream, ushort cRC_16)

{

ushort cRC_temp = Convert.ToUInt16((dataStream[dataStream.Length - 1] << 8) + dataStream[dataStream.Length - 2]);

int totalBit = (dataStream.Length - 2) * 8;

for (int i = totalBit - 1; i >= 0; i--)

{

ushort a = Convert.ToUInt16(i / 8);

ushort b = Convert.ToUInt16(i % 8);

ushort nextBit = Convert.ToUInt16((dataStream[a] >> b) & 0x01);

if (cRC_temp >= 32768)

{

cRC_temp = Convert.ToUInt16(((cRC_temp - 32768) << 1) + nextBit);

cRC_temp = Convert.ToUInt16(cRC_temp ^ cRC_16);

}

else

{

cRC_temp = Convert.ToUInt16((cRC_temp << 1) + nextBit);

}

}

return cRC_temp;

}

}

byte[] array = new byte[] { 0, 0, 157 };

ushort cRC_Result = CRCVerifyLHY.GetCRC(array, 0x1021);

Console.WriteLine(cRC_Result);

Console.ReadKey();

60.判断是否为空文件

//using System.IO;

StreamReader sr = new StreamReader(aFile);

string str;

while ((str = sr.ReadLine()) != null)

{

str = str.Trim();

if (str != null)

{

sr.Close();

//空白文件

}

}

sr.Close();

61.终止程序

//using System.Diagnostics;

Process[] killprocess = System.Diagnostics.Process.GetProcessesByName(%%1); //"calc"

foreach (System.Diagnostics.Process p in killprocess)

{

p.Kill();

}

62.定时关机

/*

using System.Diagnostics;

using System.Management;

using System.Runtime.InteropServices;

[DllImport("kernel32.dll",ExactSpelling=true)]

internal static extern IntPtr GetCurrentProcess();

[DllImport("advapi32.dll", ExactSpelling=true, SetLastError=true) ]

internal static extern bool OpenProcessToken( IntPtr h, int acc, ref IntPtr phtok );

[DllImport("advapi32.dll", SetLastError=true) ]

internal static extern bool LookupPrivilegeValue( string host, string name, ref long pluid );

[DllImport("advapi32.dll", ExactSpelling=true, SetLastError=true) ]

internal static extern bool AdjustTokenPrivileges( IntPtr htok, bool disall, ref TokPriv1Luid newst, int len, IntPtr prev, IntPtr relen );

[DllImport("user32.dll", ExactSpelling=true, SetLastError=true) ]

internal static extern bool ExitWindowsEx( int flg, int rea);

internal const int SE_PRIVILEGE_ENABLED = 0x00000002;

internal const int TOKEN_QUERY = 0x00000008;

internal const int TOKEN_ADJUST_PRIVILEGES = 0x00000020;

internal const string SE_SHUTDOWN_NAME = "SeShutdownPrivilege";

//注销参数 中止进程,然后注销

internal const int EWX_LOGOFF = 0x00000000;

//重启参数 重新引导系统

internal const int EWX_REBOOT = 0x00000002;

//公用参数 强迫中止没有响应的进程

internal const int EWX_FORCE = 0x00000004;

//关机参数

internal const int EWX_POWEROFF = 0x00000008;

//此参数没有用到 关闭系统

internal const int EWX_SHUTDOWN = 0x00000001;

//此参数没有用到

internal const int EWX_FORCEIFHUNG = 0x00000010;

private int second = 0;

*/

///

/// 主函数

///

///

private static void DoExitWin( int flg )

{

//在进行操作之前关掉用户级别的进程。

KillUserProcess();

bool ok;

TokPriv1Luid tp;

IntPtr hproc = GetCurrentProcess();

IntPtr htok = IntPtr.Zero;

ok = OpenProcessToken( hproc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref htok );

tp.Count = 1;

tp.Luid = 0;

tp.Attr = SE_PRIVILEGE_ENABLED;

ok = LookupPrivilegeValue( null, SE_SHUTDOWN_NAME, ref tp.Luid );

ok = AdjustTokenPrivileges( htok, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero );

ok = ExitWindowsEx( flg, 0 );

}

///

/// 关机

///

public static void PowerOff()

{

DoExitWin( EWX_FORCE | EWX_POWEROFF );

}

///

/// 注销

///

public static void LogoOff()

{

DoExitWin ( EWX_FORCE | EWX_LOGOFF );

}

///

/// 重启

///

public static void Reboot()

{

DoExitWin( EWX_FORCE | EWX_REBOOT );

}

///

/// 计时器

///

///

///

private void timer1_Tick(object sender, System.EventArgs e)

{

if (second > 0)

{

this.labelSecond.Text = GetTimeString( second ).ToString();

second--;

if( second == 0)

{

//关机

PowerOff() ;

}

}

}

[StructLayout(LayoutKind.Sequential, Pack=1)]

internal struct TokPriv1Luid

{

public int Count;

public long Luid;

public int Attr;

}

///

/// 依据指定的秒数换算出等价的小时分钟和秒

///

///

///

private string GetTimeString( int s )

{

//小时

int lastHours = s/3600 ;

//分钟

int lastMinute = (s%3600)/60;

//秒

int lastSecond = (s%3600)%60;

//用于显示的字符串

string timeShow = "";

timeShow = timeShow + "";

if( lastHours == 0)

{

//说明此种情况不够1小时

if(lastMinute == 0)

{

//说明此情况不足1分钟

timeShow = timeShow + lastSecond +"秒";

}

else

{

timeShow = timeShow + lastMinute +"分钟 ";

timeShow = timeShow + lastSecond +"秒";

}

}

else

{

//说明超过1小时

timeShow = timeShow + lastHours +"小时 ";

timeShow = timeShow + lastMinute +"分钟 ";

timeShow = timeShow + lastSecond +"秒";

}

return timeShow.ToString();

}

///

/// 关掉用户级别的进程

///

private static void KillUserProcess()

{

//取得当前计算机的用户名称

string computerName = System.Net.Dns.GetHostName();

//依据计算机的名称取得当前运行的进程并保存于一个数组中

Process []remoteAll = Process.GetProcesses( computerName );

Process processTemp = new Process();

SelectQuery query1 = new SelectQuery("Select * from Win32_Process");

ManagementObjectSearcher searcher1 = new ManagementObjectSearcher(query1);

string text1 = "";

text1 += "当前运行进程总数:"+remoteAll.Length.ToString()+"\n";

//进程次序

int iCount = 0;

try

{

foreach (ManagementObject disk in searcher1.Get())

{

ManagementBaseObject inPar = null;

ManagementBaseObject outPar = null;

inPar = disk.GetMethodParameters("GetOwner");

outPar = disk.InvokeMethod("GetOwner", inPar,null);

//依据ID号获取进程

processTemp = Process.GetProcessById( Convert.ToInt32(disk["ProcessId"].ToString()));

//如果是用户的进程就把该进程关掉

if(outPar["Domain"] != null)

{

if(outPar["Domain"].ToString().ToLower() == computerName )

{

// //去掉两个进程不能关掉

if((processTemp.ProcessName.ToString().ToLower()!="explorer") && (processTemp.ProcessName.ToString().ToLower() !="ctfmon")&& (processTemp.ProcessName.ToString().ToLower() !="closemachine") )

{

processTemp.Kill();

}

}

}

// text1 += "进程" +(++iCount)+": ProcessName="+processTemp.ProcessName.ToString() + ",User="+outPar["User"]+",Domain="+outPar["Domain"]+"\n";

}

}

catch (Exception ex)

{

text1 = ex.Message;

}

// this.label1.Text = str;

}

//预定关机时间

DateTime time1 = DateTime.Now;

//预定关机时间的日期 年月日

string time1Front = %%1; //time1.ToShortDateString()

//预定关机时间的小时

string time1Hour = %%2;

//预定关机时间的分钟

string time1Minute = %%3;

string b = time1Front +" "+ time1Hour +":"+time1Minute;

time1 = Convert.ToDateTime( b );

//当前时间

DateTime time2 = DateTime.Now;

//求出两个时间差

TimeSpan time3 = time1 - time2;

//计算两个时间相错的描述

string c = time3.TotalSeconds.ToString("#00");

if( Convert.ToInt32( c ) <= 0)

{

MessageBox.Show("请重新选择当前时间之后的时间为自动关机时间。");

}

second = Convert.ToInt32(c);

63.显示进程列表

//using System.Diagnostics;

Process[] processes;

processes = System.Diagnostics.Process.GetProcesses();

Process process;

for(int i = 0;i

{

process = processes[i];

//process.Id

//process.ProcessName

}

64.遍历文件夹列出文件大小

65.目录下所有文件移动到整合操作

/*

using System.IO;

using System.Collections;

*/

FolderDialog aa = new FolderDialog();

aa.DisplayDialog();

if (aa.Path != "")

{

string direc = %%1;//获取选中的节点的完整路径

foreach (string fileStr in Directory.GetFiles(direc))

File.Move((direc.LastIndexOf(Path.DirectorySeparatorChar) == direc.Length - 1) ? direc + Path.GetFileName(fileStr) : direc + Path.DirectorySeparatorChar + Path.GetFileName(fileStr), (aa.Path.LastIndexOf(Path.DirectorySeparatorChar) == aa.Path.Length - 1) ? aa.Path + Path.GetFileName(fileStr) : aa.Path + Path.DirectorySeparatorChar + Path.GetFileName(fileStr));

DirectoryInfolistView.Clear();

}

66.对目标压缩文件解压缩到指定文件夹

/*

using System.Runtime.Serialization;

using System.Runtime.Serialization.Formatters.Binary;

using System.Collections;

System.Design.dll

using System.IO.Compression;

*/

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

}

}

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值