Visual C#通用范例开发金典
上QQ阅读APP看本书,新人免费读10天
设备和账号都新为新人

第3章 文件系统

● 文件对象

● 文件的查找

● 文件的读取与保存

● 文件的复制与移动

● 解密与加密

● 文件目录

● 文件的修改与删除

● 其他相关应用

3.1 文件对象

本节着重讲解如何操作不同的文件对象,为修改、添加和删除文件做准备。

范例3-1 Excel文件操作

实例位置:光盘\ch03\3-1

范例说明

About the Example

过将ListView中的数据显示在程序创建的Excel文件中,来说明如何对Excel文件进行操作。程序运行效果如图3-1~图3-3所示。

图3-1 修改Columns属性

图3-3 填充到Excel文件效果

关键步骤

Key Steps

1.创建新的Windows应用程序。

2.放置控件及移动位置。新建1个ListView、1个Button,并调整位置。

3.其他属性的修改。

1)ListView属性修改。修改Columns属性,如图3-1所示。

2)在属性栏中修改相应控件的属性即可(这里修改Text属性)。

程序代码

Codes

1.为ListView填充数据

private void BindDate()
{    //填充表格数据内容
    int itemNumber=this.listView1.Items.Count;
    //获取当前List中项目个数
    string[] Item0={"71103101","杨雪","80"};
    this.listView1.Items.Insert(itemNumber,new ListViewItem(Item0));
    //用Insert(int,ListViewItem)方法向list中添加项目,其中int代表插入
    //位置,ListViewItem代表插入项目
    //下面代码见源程序
}

2.将数据填充到Excel文件中

private void button1_Click(object sender, System.EventArgs e)
{   //保存为EXCEL文件
    if(this.listView1.Items.Count<1)
          return;
    //如果ListView中没有填充数据,则不操作
    try
    {
          Excel.ApplicationClass MyExcel=new Excel.ApplicationClass();
          //创建Excel组件对象
          MyExcel.Visible=true;
          //设置为可见
          if(MyExcel==null)
          {    //如果返回为null,则说明创建对象失败
              MessageBox.Show("EXCEL无法启动!","信息提示",
                  MessageBoxButtons.OK,MessageBoxIcon.Information);
              return;
          }
          Excel.Workbooks MyWorkBooks = MyExcel.Workbooks;
          //获取工作簿
          Excel.Workbook MyWorkBook = MyWorkBooks.Add(Missing.Value);
          //添加新文件
          Excel.Worksheet MyWorkSheet = (Excel.Worksheet)MyWorkBook.Worksheets[1];
          //创建新表单
          Excel.Range MyRange = MyWorkSheet.get_Range("A1","C1");
          //在MyWorkSheet中获取起始单元格为A1结束单元格为C1的范围
          object [] MyHeader = {"学号","姓名","成绩"};
          MyRange.Value2= MyHeader;
          //将值赋给该范围,即A1显示"学号",B1"姓名",C1"成绩"
          if (this.listView1.Items.Count >0)
          {
              MyRange =MyWorkSheet.get_Range("A2",Missing.Value);
              //在MyWorkSheet中获取起始单元格为A2的无限范围
              object [,] MyData = new Object[this.listView1.Items.Count,3];
              //创建一个2维数组,用来存放ListView中的数据
              foreach(ListViewItem lvi in this.listView1.Items)
              {
                  MyData[lvi.Index,0] = lvi.Text;
                  MyData[lvi.Index,1] = lvi.SubItems[1].Text;
                  MyData[lvi.Index,2] = lvi.SubItems[2].Text;
              }
              //将数组依次赋值
              MyRange = MyRange.get_Resize(this.listView1.Items.Count,3);
              //在MyWorkSheet中获取起始单元格为A2的行数为this.listView1.Items
              //.Count,列数为3的矩阵的范围
              MyRange.Value2= MyData;
              //将2维数组赋值给范围
              MyRange.EntireColumn.AutoFit();
              //单元格自动调整到与数据相适应的大小
        }
        MyExcel= null;
    }
    catch(Exception Err)
    {
        MessageBox.Show("调用EXCEL程序时出现错误!"+Err.Message,"信息提示",
            MessageBoxButtons.OK,MessageBoxIcon.Information);
    }
}

提示:

注意理解Excel类的组成结构和创建顺序。先有工作簿,然后添加文件,接着添加工作表。

范例3-2 Word文件操作

实例位置:光盘\ch03\3-2

范例说明

About the Example

范例通过将文本框中的文字保存为Word文件,来说明对Word文件的相关操作方法,程序运行效果如图3-4和图3-5所示。

图3-4 Excel文件操作界面

图3-5 填充到Excel文件效果

关键步骤

Key Steps

1.创建新的Windows应用程序。

2.放置控件及移动位置。新建1个RichTextBox、1个Label及1个Button,并调整位置。

3.其他属性的修改。在属性栏中修改相应控件的属性即可(这里修改Text属性)。

程序代码

Codes

private void button1_Click(object sender, System.EventArgs e)
{//另存为WORD文件
    if(this.richTextBox1.Text=="")
          return;
    if(this.saveFileDialog1.ShowDialog()==DialogResult.Cancel)
          return;
    string FileName=this.saveFileDialog1.FileName;
    if(FileName.Length<1)
                      return;
    FileName+=".doc";
    try
    {
          Word.ApplicationClass MyWord=new Word.ApplicationClass();
          //创建WordApp组件对象
          Word.Document MyDoc;
          //创建Word文档对象
          Object Nothing=System.Reflection.Missing.Value;
          //创建空Object对象以填充参数
          MyDoc=MyWord.Documents.Add(ref Nothing,ref Nothing,ref Nothing,ref
          Nothing);
          //初始化Word文档对象
          MyDoc.Paragraphs.Last.Range.Text=this.richTextBox1.Text;
          //将文本框中的文件赋值给Word文档对象的相应参数
          object MyFileName=FileName;
          MyDoc.SaveAs(ref MyFileName,ref Nothing,ref Nothing,ref Nothing,ref
          Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref
          Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing);
          //将Word文档对象的内容保存为DOC文档 ,并用Nothing填充无用参数
          MyDoc.Close(ref Nothing, ref Nothing, ref Nothing);
          //关闭Word文档对象
          MyWord.Quit(ref Nothing, ref Nothing, ref Nothing);
          //关闭WordApp组件对象
          MessageBox.Show("保存成功","信息提示",
          MessageBoxButtons.OK,MessageBoxIcon.Information);
    }
          catch(Exception Err)
          {
              MessageBox.Show("保存失败!"+Err.Message,"信息提示",
    MessageBoxButtons.OK,MessageBoxIcon.Information);
          }
    }

范例3-3 获取和设置文件属性

实例位置:光盘\ch03\3-3

范例说明

About the Example

范例讲解获取和设置控件并修改相关属性。程序运行效果如图3-6所示。

图3-6 获取和设置文件属性操作界面

函数说明

About the Function

1.File.SetAttributes(string str, FileAttributes attri),str为文件路径,attri为文件的属性。

2.File.GetLastWriteTime(string str)为获取文件最后修改时间,返回一个字符串。

3.File.GetLastAccessTime(string str)为获取文件最后读取时间,返回一个字符串。

4.File.GetAttributes(string str)为获取文件当前属性,返回FileAttributes,str为文件路径。

关键步骤

Key Steps

1.创建新的Windows应用程序。

2.放置控件及移动位置。新建5个CheckBox、3个DateTimePicker、3个Button及1个TextBox,并调整控件的位置。

3.其他属性的修改。在属性栏中修改相应控件的属性即可(这里修改Text属性)。

程序代码

Codes

1.读取文件属性

private void button2_Click(object sender, System.EventArgs e)
{   //获取文件属性
    this.checkBox1.Checked=false;
    this.checkBox2.Checked=false;
    this.checkBox3.Checked=false;
    this.checkBox4.Checked=false;
    this.checkBox5.Checked=false;
    //将所有CheckBox都设置为未选中
    if(this.textBox1.Text.Length<2)
          return;
    //如果获取的文件路径无效则不做任何动作
    this.dateTimePicker1.Text=
    File.GetCreationTime(this.textBox1.Text).ToLongDateString();
    //通过File.GetCreationTime(string)获取文件创建时间
    this.dateTimePicker2.Text=
    File.GetLastWriteTime(this.textBox1.Text).ToLongDateString();
    //通过File.GetLastWriteTime(string)获取文件最后修改时间
    this.dateTimePicker3.Text=
    File.GetLastAccessTime(this.textBox1.Text).ToLongDateString();
    //通过File.GetLastAccessTime(string)获取文件最后读取时间
    FileAttributes MyAttributes=File.GetAttributes(this.textBox1.Text);
    //通过File.GetAttributes(string)获取文件当前属性
    string MyFileType=MyAttributes.ToString();
    //将MyAttributes.ToString()会以字符串的形式返回文件的属性。
    if(MyFileType.LastIndexOf("ReadOnly")!=-1)
    {//如果字符串中包含ReadOnly,则说明文件为只读,反之则非只读
        this.checkBox1.Checked=true;
    }
    if(MyFileType.LastIndexOf("System")!=-1)
    {//系统
        this.checkBox2.Checked=true;
    }
    if(MyFileType.LastIndexOf("Hidden")!=-1)
    {//隐藏
        this.checkBox3.Checked=true;
    }
    if(MyFileType.LastIndexOf("Archive")!=-1)
    {//存档
        this.checkBox4.Checked=true;
    }
    if(MyFileType.LastIndexOf("Temporary")!=-1)
    {//临时
        this.checkBox5.Checked=true;
    }
}

2.设置文件属性

private void button3_Click(object sender, System.EventArgs e)
{   //设置文件属性
    if(this.textBox1.Text.Length<2)
          return;
    //如果获取的文件路径无效,则不做任何动作
    File.SetAttributes(this.textBox1.Text, FileAttributes.Normal);
    //通过File.SetAttributes方法设置文件属性,第一个参数代表目标文件路径,第二
    //个参数代表某项文件属性,如FileAttributes.Normal代表普通文件
    if(this.checkBox1.Checked==true)
    {
          File.SetAttributes(this.textBox1.Text, FileAttributes.ReadOnly);
    }
    FileAttributes MyAttributes=File.GetAttributes(this.textBox1.Text);
    //通过File.GetAttributes(string)获取文件当前属性
    if(this.checkBox2.Checked==true)
    {
          File.SetAttributes(this.textBox1.Text,MyAttributes|
          FileAttributes.System);
          //使文件具有之前的属性并添加属性FileAttributes.System (系统文件)
    }
    MyAttributes=File.GetAttributes(this.textBox1.Text);
    if(this.checkBox3.Checked==true)
    { //隐藏
          File.SetAttributes(this.textBox1.Text,MyAttributes|
          FileAttributes.Hidden);
    }
    MyAttributes=File.GetAttributes(this.textBox1.Text);
    if(this.checkBox4.Checked==true)
    { //存档
          File.SetAttributes(this.textBox1.Text,MyAttributes|
          FileAttributes.Archive);
    }
    MyAttributes=File.GetAttributes(this.textBox1.Text);
    if(this.checkBox5.Checked==true)
    { //临时
          File.SetAttributes(this.textBox1.Text,MyAttributes|
    FileAttributes.Temporary);
    }
    File.SetCreationTime(this.textBox1.Text,this.dateTimePicker1.Value);
    //通过File.SetCreationTime(string,DateTime)设置创建时间
    File.SetLastWriteTime(this.textBox1.Text,this.dateTimePicker2.Value);
    //通过File.SetLastWriteTime(string,DateTime)设置最后修改时间
    File.SetLastAccessTime(this.textBox1.Text,this.dateTimePicker3.Value);
    //通过File.SetLastAccessTime(string,DateTime)设置最后访问时间
    MessageBox.Show("设置文件属性操作成功!","信息提示",
    MessageBoxButtons.OK,MessageBoxIcon.Information);
}

范例3-4 获取可执行文件信息

实例位置:光盘\ch03\3-4

范例说明

About the Example

范例通过获取指定可执行文件的信息,来说明对可执行文件的相关属性的操作。程序运行效果如图3-7所示。

图3-7 获取可执行文件信息操作界面

函数说明

About the Function

FileVersionInfo.GetVersionInfo(string str)为返回文件信息FileVersionInfo的实例,str为文件的路径。

关键步骤

Key Steps

1.创建新的Windows应用程序。

2.放置控件及移动位置。

3.其他属性的修改。在属性栏中修改相应控件的属性即可(这里修改Text属性)。

程序代码

Codes

private void ShowInfo()
{   //获取程序文件信息
    string MyFileName=this.textBox1.Text;
    if(MyFileName.Length<1)
          return;
    //如果文件路径无效则不做任何操作
    string ShortName=MyFileName.Substring(MyFileName.LastIndexOf("\\")+1);
    //获取可执行文件名
    FileVersionInfo MyInfo=FileVersionInfo.GetVersionInfo(MyFileName);
    //使用FileVersionInfo.GetVersionInfo(string)赋值给FileVersionInfo的实例
    //MyInfo
    this.label1.Text="公司名称:"+MyInfo.CompanyName;
    this.label2.Text="产品名称:"+MyInfo.ProductName;
    this.label3.Text="语言标志:"+MyInfo.Language;
    this.label4.Text="版本号:"+MyInfo.FileVersion;
    this.label5.Text="版权声明:"+MyInfo.LegalCopyright;
    //读取FileVersionInfo的成员值
}
如果是获取当前程序的信息则有以下代码:
private void ShowSelfInfo()
{   //获取当前程序文件信息
    this.label1.Text="公司名称:"+Application.CompanyName;
    this.label2.Text="区域信息:"+Application.CurrentCulture;
    this.label3.Text="语言标志:"+Application.CurrentInputLanguage;
    this.label4.Text="产品名称:"+Application.ProductName;
    this.label5.Text="产品版本:"+Application.ProductVersion;
}

范例3-5 获取文件和文件夹的目录信息

实例位置:光盘\ch03\3-5

范例说明

About the Example

范例将介绍获取文件及文件架路径属性的方法。程序运行效果如图3-8所示。

图3-8 目录信息操作界面

函数说明

About the Function

1.System.IO.Directory.GetDirectoryRoot(string str)为获取根目录,str为输入的路径。

2.System.IO.Directory.GetParent(string str)为获取父目录,str为输入的路径。

关键步骤

Key Steps

1.创建新的Windows应用程序。

2.放置控件及移动位置。新建5个Label、1个TextBox及2个Button,并调整位置。

3.其他属性的修改。在属性栏中修改相应控件的属性即可(这里修改Text属性)。

程序代码

Codes

1.获取指定路径的根目录信息

if(this.textBox1.Text.Trim()=="")
          return;
string MyRoot=System.IO.Directory.GetDirectoryRoot(this.textBox1.Text);
//通过System.IO.Directory.GetDirectoryRoot(string)方法获取根目录信息
this.label2.Text=MyRoot;

2.获取指定路径的父目录信息

try
{
          System.IO.DirectoryInfo MyInfo=
    System.IO.Directory.GetParent(this.textBox1.Text);
          //通过System.IO.Directory.GetParent(string)方法获取根目录信息
          this.label3.Text=MyInfo.FullName;
}
catch(Exception Err)
{
          MessageBox.Show("不要只选择根目录!","信息提示",
          MessageBoxButtons.OK,MessageBoxIcon.Information);
}

范例3-6 判断文件及文件夹是否存在

实例位置:光盘\ch03\3-6

范例说明

About the Example

范例通过File类的接口,判断用户输入的文件或文件夹是否在指定路径上存在。程序运行效果如图3-9和图3-10所示。

图3-9 判断文件是否存在

图3-10 判断文件夹是否存在

函数说明

About the Function

File.Exists(string str)为判断该路径是否存在,str为待判断的路径。

关键步骤

Key Steps

1.创建新的Windows应用程序。

2.放置控件及移动位置。

1)放置控件。新建2个TextBox、2个Label、2个Button、1个TabControl及一个FolderBrowserDialog,将控件放入相应的TabPage中,并调整位置。

2)TabControl的设计。选定TableControl控件,然后在属性栏中单击项目TabPages,然后在TabPagees集合编辑器中添加或移除页,或对页的属性进行修改(修改Text属性)。

3.其他属性的修改。在属性栏中修改相应控件的属性即可(这里修改Text属性)。

程序代码

Codes

1.文件判断

private void button1_Click(object sender, System.EventArgs e)
{   //判断文件是否已经存在
    string MyFileName=this.textBox1.Text;
    if(MyFileName.Length<1)
          return;
    //如果输入的文件路径无效,则不采取操作
    string ShortName=MyFileName.Substring(MyFileName.LastIndexOf("\\")+1);
    //获取文件名
    if(File.Exists(MyFileName))
    {//调用File.Exists(string)方法判断是否存在
          MessageBox.Show("文件:"+ShortName+"已经存在!","信息提示",
            MessageBoxButtons.OK,MessageBoxIcon.Information);
    }
    else
    {
          MessageBox.Show("文件:"+ShortName+"不存在!","信息提示",
          MessageBoxButtons.OK,MessageBoxIcon.Information);
    }
}

2.文件夹判断

private void button2_Click(object sender, System.EventArgs e)
{   //判断文件夹是否已经存在
    string MyFolderName=this.textBox2.Text;
    if(MyFolderName.Length<1)
          return;
    //如果输入的文件夹路径无效,则不采取操作
    string FolderName=
      MyFolderName.Substring(MyFolderName.LastIndexOf("\\")+1);
    //获取文件夹名
    if(Directory.Exists(MyFolderName))
    {//调用Directory.Exists(string)方法判断是否存在
          MessageBox.Show("文件夹:"+FolderName+"已经存在!","信息提示",
          MessageBoxButtons.OK,MessageBoxIcon.Information);
    }
    else
    {
          MessageBox.Show("文件夹:"+FolderName+"不存在!","信息提示",
          MessageBoxButtons.OK,MessageBoxIcon.Information);
    }
}

范例3-7 文件的分割与合并

实例位置:光盘\ch03\3-7

范例说明

About the Example

范例是一个文件分割与合并的工具,它可以将文件按指定大小分割为多块,并且将其重新组合起来。程序运行效果如图3-11~图3-13所示。

图3-11 修改TabControl属性

图3-13 合并文件界面

图3-12 分割文件界面

函数说明

About the Function

1.FileStream.Read(byte [] buffer,int offset,int count)可以将数据从流中读取出来,返回值为读取到的数据的长度。buffer为接受数据的数组,offset为读取的偏移量,一般为0,count为读取的长度。

2.FileStream.Write(byte [] buffer,int offset,int count);可以将数据写入流。buffer为待写入的数据的数组,offset为写入的偏移量,一般为0,count为写入的长度。

关键步骤

Key Steps

1.创建新的Windows应用程序。

2.放置控件及移动位置。

1)放置控件

在窗体上新建7个TextBox、7个Label、4个Butiton、1个TabControl,并调整其位置,将控件放入对应的TabPage中。

2)TabControl的设计

选定TableControl控件,然后在属性栏中单击项目TabPages,然后在TabPages集合编辑器中添加或移除页,或对页的属性进行修改(这里修改Text属性)。如图3-11所示。

3.其他属性的修改。在属性栏中修改相应控件的属性即可(这里修改Text属性)。

程序代码

Codes

1.如何分割文件

private void button2_Click(object sender, System.EventArgs e)
{   /分割文件
    try
    {
          FileStream MyInFile=
          new FileStream(this.textBox1.Text,FileMode.OpenOrCreate,
          FileAccess.Read);
          //读取要分割的文件,FileMode.OpenOrCreate属性则代表如果没有则创建,否则打开,
          //FileAccess.Read属性则代表只能对该文件进行写操作
          for (int i = 0; i<Int32.Parse(this.textBox3.Text) ; i++)
          //通过循环将文件分割为指定的块
          {
              FileStream MyOutFile =
              new FileStream(this.textBox1.Text+i+".fh",
              FileMode.OpenOrCreate, FileAccess.Write);
              //新建输出文件,注意参数i规定了分割后文件的编号,FileMode.OpenOrCreate属
              //性则代表如果没有则创建,否则打开,FileAccess.Write,属性则代表可对该文件
              //进行写操作
              int data=0;
              int FileSize=Convert.ToInt32(this.textBox4.Text);
              //得到分块大小
              byte [] buffer = new byte [FileSize];
              if ((data=MyInFile.Read(buffer,0,FileSize))>0)
              {//根据分块大小读取数据
                  MyOutFile.Write(buffer,0,data);
                  //将读取的数据写入分块
              }
              MyOutFile.Close();
          }
          MyInFile.Close();
          MessageBox.Show("切分文件操作完成!","信息提示",
          MessageBoxButtons.OK,MessageBoxIcon.Information);
    }
    catch(Exception Err)
    {
          MessageBox.Show("切分文件出现错误:"+Err.Message,"信息提示",
          MessageBoxButtons.OK,MessageBoxIcon.Information);
    }
}

2.如何合并文件

private void button3_Click(object sender, System.EventArgs e)
{   //合并分割文件
    try
    {
          FileStream MyOutFile =
          new FileStream(this.textBox6.Text,FileMode.OpenOrCreate,
          FileAccess.Write);
          //创建输出文件
          for (int i=0;i<Int32.Parse(this.textBox7.Text); i++)
          {
              int data=0;
              byte [] buffer = new byte [1024];
              string FileName=this.textBox5.Text.Substring(0,
              this.textBox5.Text.Length-4);
              //得到各个分块的路径
              FileStream MyInFile =
              new FileStream(FileName+i+".fh",FileMode.OpenOrCreate,
              FileAccess.Read);
              //打开各个分块
              while ((data=MyInFile.Read(buffer,0,1024))>0)
              {//读取分块数据
                  MyOutFile.Write(buffer,0,data);
                  //写入输出文件
              }
                  MyInFile.Close();
          }
          MyOutFile.Close();
          MessageBox.Show("组合文件操作完成","信息提示",MessageBoxButtons.OK,
          MessageBoxIcon.Information);
      }
      catch(Exception Err)
      {
          MessageBox.Show("组合文件出现错误:"+Err.Message,"信息提示",
          MessageBoxButtons.OK,MessageBoxIcon.Information);
      }
}

范例3-8 使用EXE文件

实例位置:光盘\ch03\3-8

范例说明

About the Example

范例通过代码来执行外部EXE文件。程序运行效果如图3-14所示。

图3-14 调用外部EXE界面

函数说明

About the Function

System.Diagnostics.Process.Start(ProcessStartInfo p) 执行文件,P为待执行的文件的信息。

关键步骤

Key Steps

1.创建新的Windows应用程序。

2.放置控件及移动位置。新建1个TextBox、1个Label、1个OpenFileDialog及1个Button,并调整位置。

3.其他属性的修改。在OpenFileDialog中修改Filter属性,使只显示EXE文件,在属性栏中修改相应控件的属性即可(这里修改Text属性)。

4.添加库文件。在代码头部添加“using System.Diagnostics;”,然后在类内添System.Diagnostics.ProcessStartInfo p = null; 和System.Diagnostics.Process Proc。System.Diagnostics.ProcessStartInfo为应用程序的信息,包括路径、名称和启动参数,System.Diagnostics.Process为进程类,用来操作进程。

程序代码

Codes

private void button1_Click(object sender, EventArgs e)
{
      //获取要打开的EXE文件的路径和名称
      this.openFileDialog1.ShowDialog();
      this.filePath.Text = this.openFileDialog1.FileName;
      int index=this.filePath.Text.LastIndexOf(@"\");
      string name = this.filePath.Text.Substring(index+1,
                    this.filePath.Text.Length - index-1);
      string path = this.filePath.Text.Substring(0, index);
      //创建打开信息
      p = new ProcessStartInfo(name);
      //设置此外部程序所在的windows目录
      p.WorkingDirectory = path;
      //在调用外部exe程序的时候,控制台窗口不弹出
      p.WindowStyle = ProcessWindowStyle.Hidden;
      //如果想获得当前路径为
      //string path = System.AppDomain.CurrentDomain.BaseDirectory;
      //可调用外部程序
      Proc  =  System.Diagnostics.Process.Start(p);
      //可以利用Proc.HasExited为true or false来判断外部程序是否还在运行
}

范例3-9 获取EXE文件的路径信息

实例位置:光盘\ch03\3-9

范例说明

About the Example

范例实现了获取本程序的EXE路径信息。程序运行效果如图3-15所示。

图3-15 获取到当前EXE文件的路径信息效果

函数说明

About the Function

System.Reflection.Assembly.GetExecutingAssembly(); 为获取程序的信息。

关键步骤

Key Steps

1.创建新的Windows应用程序。

2.放置控件及移动位置。新建1个Label并调整位置。

3.其他属性的修改。在属性栏中修改相应控件的属性即可。

程序代码

Codes

private void ShowInfo()
{
    //得到可执行文件的路径(包括名称)
    this.label1.Text = "可执行文件的路径\n" + Application.ExecutablePath+"\n";
    //获取最初指定程序的位置
    this.label1.Text += "最初指定程序的位置\n" +
    System.Reflection.Assembly.GetExecutingAssembly().CodeBase + "\n";
    //获取程序的路径(包括名称)
    this.label1.Text += "程序的路径\n" +
    System.Reflection.Assembly.GetExecutingAssembly().Location + "\n";
    //获取程序的路径(不包括程序名称)
    string hostName= "程序的路径(不包括程序名称)\n" +
    System.Reflection.Assembly.GetExecutingAssembly().Location + "\n";
    hostName = "" + hostName.Substring(0, hostName.LastIndexOf('\\')) + "\n";
    this.label1.Text += hostName;
    //获取程序的名称(不包括程序后缀)通常是程序集的名称,如果可执行文件改名了,就要通过分析路
    //径得到文件名
    this.label1.Text += "获取程序的名称(不包括程序后缀)\n" +
    System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;
}

3.2 文件的查找

本节着重讲解文件进行查找的方法及查找中可能用到的技巧。

范例3-10 文件搜索器

实例位置:光盘\ch03\3-10

范例说明

About the Example

范例通过遍历文件夹来查找文件的位置。程序运行效果如图3-16和图3-17所示。

图3-16 文件搜索界面

图3-17 查找到文件

函数说明

About the Function

1.DirectoryInfo.GetDirectories(); 为返回该目录中的文件夹数组。

2.DirectoryInfo.GetFiles(string str); 为返回该目录中符合条件的文件的数组,str为文件的条件。

关键步骤

Key Steps

1.创建新的Windows应用程序。

2.放置控件及移动位置。新建1个TextBox、2个Label、1个ComboBox、1个ListView及2个Button,并调整位置。

3.其他属性的修改。在属性栏中修改相应控件的属性即可,注意ComboBox的数据是在程序初始化时候通过调用AddComboBoxItem(String [] strDrives)来添加的,而ListView则是在Column属性中添加各个栏目的。

程序代码

Codes

private void btnStart_Click(object sender, System.EventArgs e)
 {
          lvResult.Items.Clear();
          if((txtSearchFileName.Text=="")&&(cmbDrives.Text==""))
          {
              MessageBox.Show("选择一个驱动器,然后输入文件名!");
          }
          else if(txtSearchFileName.Text=="")
          {
              MessageBox.Show("输入文件名!");
          }
          else if(cmbDrives.Text=="")
          {
              MessageBox.Show("选择一个驱动器!");
          }
          else
          {
              try
                  {
                      int i=0;
                      int iVal;
                      //获取制定目录下的子文件夹
                      DirectoryInfo []ChildDirs=
                          this.getDirectories(cmbDrives.Text);
                      //如果搜索的文件名没有扩展名,则后面加上".*"
                      iVal=txtSearchFileName.Text.IndexOf(".");
                      if(iVal==-1)
                      {
                            txtSearchFileName.Text+=".*";
                      }
                      //取得子更下级的文件加信息
                      DirectoryInfo ChildDir;
                      foreach(DirectoryInfo di in ChildDirs)
                      {
                            ChildDir=di;
                            //递归搜索子文件夹
                            while(ChildDir.GetDirectories().Length>0)
                            {
                                DirectoryInfo []GrandChilds=
                                    ChildDir.GetDirectories();
                                foreach(DirectoryInfo GrandChild in GrandChilds)
                                {
                                    FileInfo [] Files =
                                    GrandChild.GetFiles(txtSearchFileName.Text);
                                    if(Files.Length==0)
                                    {
                                    }
                                    else
                                    {    //获取每个文件夹中文件的信息
                                          foreach(FileInfo DirFile in Files)
                                          {
                                              AddListViewItem(DirFile.Name,
                                              DirFile.Directory.FullName,
                                              DirFile.Length.ToString(),
                                    DirFile.LastWriteTime.ToShortDateString());
                                              i++;
                                          }
                                    }
                                    ChildDir=GrandChild;
                                }
                            }
                        }
                  }
                  catch(IOException ioex)
                  {
                        MessageBox.Show(ioex.Message);
                  }
                  if (lvResult.Items.Count==0)
                  {
                        MessageBox.Show("搜索完毕,没有结果可以显示。");
                  }
          }
}

范例3-11 获取文件的后缀

实例位置:光盘\ch03\3-11

范例说明

About the Example

范例将讲解如何获取文件的后缀信息。程序运行效果如图3-18所示。

图3-18 获取文件后缀信息

关键步骤

Key Steps

1.创建新的Windows应用程序。

2.放置控件及移动位置。新建2个TextBox、2个Label及1个Button,并调整位置。

3.其他属性的修改。在属性栏中修改相应控件的属性即可(这里修改Text属性)。

4.添加库文件。在代码头部加入“using System.IO;”,并在类内加入“FileInfo file =null;”,其中FileInfo为文件信息操作类,可以对文件进行各种操作。

程序代码

Codes

private void Open_Click(object sender, EventArgs e)
{
    this.openFileDialog1.ShowDialog();
    file = new FileInfo(this.openFileDialog1.FileName);
    this.path.Text = file.Directory.FullName;
    this.extend.Text = file.Extension;
}

3.3 文件的读取与保存

文件的读取与保存是经常会用到的操作,熟练掌握是很必要的。

范例3-12 以流方式读写文本文件

实例位置:光盘\ch03\3-12

范例说明

About the Example

范例将文本框中的文字通过流方式存入文本文件,并从文本文件中以流方式将信息读出来,以此来说明怎样以流方式读写文件。程序运行效果如图3-19所示。

图3-19 以流方式保存到文本文件

函数说明

About the Function

1.StreamReader.Peek()为返回下一个可用字符,但是不使用它,返回一个整数。

2.StreamReader.ReadLine()为读取一行字符,返回读取的字符串。

3.StreamReader.ReadToEnd()为一直读到结尾,返回读取的字符串。

4.StreamWriter.Write(string str)。Str为待写入字符串。

关键步骤

Key Steps

1.创建新的Windows应用程序。

2.放置控件及移动位置。新建1个TextBox和2个Button,并调整位置。

3.其他属性的修改。将TextBox的Multiline属性改为True。

4.添加库文件。在代码头部加入“using System.IO;”。

程序代码

Codes

1.写入文件

private void Read_Click(object sender, EventArgs e)
{
    FileStream fs;
    fs = new FileStream(FILE_NAME, FileMode.OpenOrCreate);
    StreamReader r = new StreamReader(fs);
    //如果还可以读取字符,则继续Peek()函数返回下一个可用字符,但是不使用它
    while (r.Peek() != -1)
    {
        //使用ReadLine()函数读取一行字符
    this.content.Text += r.ReadLine();
    }
    /* 或者使用
    this.content.Text = r.ReadToEnd();
    */
    r.Close();
    fs.Close();
    MessageBox.Show("读取结束");
}

2.读取文件

private void Write_Click(object sender, EventArgs e)
{
    FileStream fs;
    if (System.IO.File.Exists(FILE_NAME))
    {
        fs = new FileStream(FILE_NAME, FileMode.Truncate);
    }
    else
    {//如果不存在,则采用文件创建方式创建FileStream
        fs = new FileStream(FILE_NAME, FileMode.CreateNew);
    }
    StreamWriter w = new StreamWriter(fs);
    //Write()函数向FileStream中写入字符串
    w.Write(this.content.Text);
    w.Close();
    fs.Close();
    MessageBox.Show("写入结束");
}

范例3-13 将数据保存到INI

实例位置:光盘\ch03\3-13

范例说明

About the Example

范例通过保存窗口的大小和标题,来说明如何将数据保存到INI文件中。程序运行效果如图3-20所示。

图3-2 Excel文件操作界面

图3-20 填充到Excel文件效果

函数说明

About the Function

1.GetPrivateProfileInt(string lpApplicationName, string lpKeyName, int nDefault, string lpFileName);

获取配置文件中的Int型参数

lpApplicationName程序标识符

lpKeyName配置类型

nDefault默认值

lpFileName配置文件路径

2.GetPrivateProfileString(string lpApplicationName, string lpKeyName, string lpDefault, StringBuilder lpReturnedString, int nSize, string lpFileName);

获取配置文件中的stirng型参数

lpApplicationName程序标识符

lpKeyName配置类型

nDefault默认值

lpReturnedString创建返回字符串

int nSize返回字符串的最大长度

lpFileName配置文件路径

3.WritePrivateProfileString(string lpApplicationName, string lpKeyName, string lpString, string lpFileName);

lpApplicationName程序标识符

lpKeyName配置类型

lpString待写入的字符串

lpFileName配置文件路径

关键步骤

Key Steps

1.创建新的Windows应用程序。

2.放置控件及移动位置。新建1个TextBox,并修改其属性。

3.添加响应事件。为Form1添加事件Load与事件FormClosing的响应函数。

4.添加库文件。在代码头部添加“using System.IO; using System.Text;”。

5.添加DLL接口引用。

在类内加入

[DllImport("kernel32")]

private static extern int GetPrivateProfileInt(string lpApplicationName, string

lpKeyName, int nDefault, string lpFileName);

[DllImport("kernel32")]

private static extern bool GetPrivateProfileString(string lpApplicationName, string

lpKeyName, string lpDefault, StringBuilder lpReturnedString, int nSize,

string lpFileName);

[DllImport("kernel32")]

private static extern bool WritePrivateProfileString(string lpApplicationName, string

lpKeyName, string lpString, string lpFileName);

[DllImport("kernel32")]

private static extern bool GetPrivateProfileSection(string lpAppName, string

lpReturnedString, int nSize, string lpFileName);

[DllImport("kernel32")]

private static extern bool WritePrivateProfileSection(string lpAppName, string lpString,

string lpFileName);

其中[DllImport("kernel32")],表示引用的是Kernel32的接口,下面的函数声明用来引用该DLL中的接口。

程序代码

Codes

private void Form1_Load(object sender, EventArgs e)
{
    if (System.IO.File.Exists(FILE_NAME))
    {
          FileStream fs;
          //以打开或创建模式创建FileStream
          fs = new FileStream(FILE_NAME, FileMode.OpenOrCreate);
          StreamReader r = new StreamReader(fs);
          //如果还可以读取字符,则继续Peek()函数返回下一个可用字符,但是不使用它
          this.content.Text = r.ReadToEnd();
          r.Close();
          fs.Close();
          StringBuilder strCaption = new StringBuilder(256);
          //获取标题
          GetPrivateProfileString("Form", "Caption", "Default Caption",
              strCaption, strCaption.Capacity, FILE_NAME);
          this.Text = strCaption.ToString();
          //获取宽度
          int myWidth = GetPrivateProfileInt("Form", "Width", this.Width,
              FILE_NAME);
          this.Width = myWidth;
          int myHeight = GetPrivateProfileInt("Form", "Height", this.Height,
              FILE_NAME);
          //获取高度
          this.Height = myHeight;
          //获取距离左面位置
          int myLeft = GetPrivateProfileInt("Form", "Left", this.Left, FILE_NAME);
          this.Left = myLeft;
          //获取距离顶部位置
          int myTop = GetPrivateProfileInt("Form", "Top", this.Top, FILE_NAME);
          this.Top = myTop;
    }
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    string strCaption = this.Text;
    //写入标题至FILE_NAME中
    WritePrivateProfileString("Form", "Caption", strCaption, FILE_NAME);
    //写入宽度至FILE_NAME中
    WritePrivateProfileString("Form", "Width", this.Width.ToString(),
          FILE_NAME);
    //写入高度至FILE_NAME中
    WritePrivateProfileString("Form", "Height", this.Height.ToString(),
          FILE_NAME);
    //写入距离左面位置至FILE_NAME中
    WritePrivateProfileString("Form", "Left", this.Left.ToString(), FILE_NAME);
    //写入距离顶部位置至FILE_NAME中
    WritePrivateProfileString("Form", "Top", this.Top.ToString(), FILE_NAME);
}

范例3-14 日志文件操作

实例位置:光盘\ch03\3-14

范例说明

About the Example

范例将说明如何对日志文件进行操作。程序运行效果如图3-21所示。

图3-21 填充到Excel文件效果

函数说明

About the Function

1.File.AppendText(string fileName)可以对文件进行追加写操作,返回一个StreamWriter类。Filename为文件路径。

2.File.OpenText(string fileName)可以对文件进行读操作,返回一个StreamReader类。Filename为文件路径。

关键步骤

Key Steps

1.创建新的Windows应用程序。

2.放置控件及移动位置。新建1个TextBox并调整位置。

3.其他属性的修改。在属性栏中修改相应控件的属性。

程序代码

Codes

1.添加日志

public  void Log(String logMessage, TextWriter w)
{
    //写入日志信息
    w.WriteLine(" 日志 : ");
    w.WriteLine(" 时间:{0} {1}", DateTime.Now.ToLongTimeString(),
          DateTime.Now.ToLongDateString());
    w.WriteLine(" 信息:{0}", logMessage);
    w.WriteLine("-------------------------------");
    w.Flush();
}

2.读取日志

public void DumpLog(StreamReader r)
{
    //读取日志信息
    String line;
    while ((line = r.ReadLine()) != null)
    {
        this.logstr.Text += line + Environment.NewLine;
    }
    r.Close();
}

范例3-15 文本文件与RichTextBox

实例位置:光盘\ch03\3-15

范例说明

About the Example

范例实现了通过RichTextBox来对Text文件进行修改。程序运行效果如图3-22所示。

图3-22 填充到Excel文件效果

函数说明

About the Function

1.RichTextBox.LoadFile(string path,RichTextBoxStreamType filetype)为加载文件,path为文件路径,filetype为流类型。

2.RichTextBox.SaveFile(string path,RichTextBoxStreamType filetype)为保存文件,path为文件路径,filetype为流类型。

关键步骤

Key Steps

1.创建新的Windows应用程序。

2.放置控件及移动位置。新建1个MenuStrip、1个RichTextBox。

3.其他属性的修改。在属性栏中修改相应控件的属性。

程序代码

Codes

this.richTextBox.LoadFile(this.openFileDialog1.FileName,
          RichTextBoxStreamType.PlainText);
this.richTextBox.SaveFile(this.saveFileDialog1.FileName,
          RichTextBoxStreamType.PlainText);

范例3-16 数据文件读写

实例位置:光盘\ch03\3-16

范例说明

About the Example

范例通过将当前时间存入.dat文件中,然后再读取,来说明如何对数据文件进行读取。程序运行效果如图3-23所示。

图3-23 读取,Dat中的时间信息

函数说明

About the Function

1.BinaryReader.ReadString()为读取字符串,返回读取的字符串。

2.BinaryReader.ReadInt64()为读取一个整型数,返回读取的整数。

3.BinaryWriter.Write(string str)为写入字符,str为待写入的字符串。

关键步骤

Key Steps

1.创建新的Windows应用程序。

2.放置控件及移动位置。新建1个TextBox、2个Button,并调整位置。

3.其他属性的修改。修改相应控件的属性,TextBox的Dock属性为“Top”,mutiline属性为“True”。

4.添加库文件。在代码头部加入“using System.IO;”。

程序代码

Codes

1.读取数据

private void Read_Click(object sender, EventArgs e)
{
    FileStream fs;
    fs = new FileStream(FILE_NAME, FileMode.OpenOrCreate);
    BinaryReader r = new BinaryReader(fs);
    //注意这里与StreamReader的不同,有更多的函数用来处理数据的读入
    this.content.Text=r.ReadString() +"      "+ r.ReadInt64().ToString();
    r.Close();
    fs.Close();
}

2.写入数据

private void Write_Click(object sender, EventArgs e)
{
    FileStream fs;
    if (System.IO.File.Exists(FILE_NAME))
    {
          fs = new FileStream(FILE_NAME, FileMode.Truncate);
    }
    else
    {    //如果文件不存在则采用创建模式创建FileStream
          fs = new FileStream(FILE_NAME, FileMode.CreateNew);
    }
    BinaryWriter w = new BinaryWriter(fs);
    //写入相应的信息
    w.Write(DateTime.Now.ToString());
    w.Write(DateTime.Now.Ticks);
    w.Close();
    fs.Close();
}

范例3-17 序列化

实例位置:光盘\ch03\3-17

范例说明

About the Example

范例将通过序列化的方法将类存入文件中。程序运行效果如图3-24所示。

图3-24 填充到Excel文件后的效果

函数说明

About the Function

1.IFormatter. Serialize(Stream stream,object graph)为序列化,stream提供写入数据的流,graph为待写入的数据。

2.IFormatter. Deserialize(Stream stream)为反序列化,返回读取的object。Stream提供读取数据的流。

关键步骤

Key Steps

1.创建新的Windows应用程序。

2.放置控件及移动位置。新建1个TextBox、2个Button,并调整位置。

3.其他属性的修改。修改相应控件的属性,TextBox的Dock属性为“Top”,mutiline属性为“True”。

4.添加库文件。在代码头部添加“using System.IO;using System.Runtime.Serialization;using System.Runtime.Serialization.Formatters.Binary;”。

5.创建序列化类。在类的前方加入 [Serializable],在本例中,在PurchaseOrder和Item前面加入,如果不想对某个参数序列化,则在该参数前加入[NonSerialized]。

程序代码

Codes

1.反序列化

private void Read_Click(object sender, EventArgs e)
{
    IFormatter formatter = new BinaryFormatter();
    Stream stream = new FileStream("MyFile.bin", FileMode.OpenOrCreate,
          FileAccess.Read, FileShare.Read);
    //反序列化
    PurchaseOrder obj = (PurchaseOrder)formatter.Deserialize(stream);
    foreach (Item i in obj.ItemsOrders)
    {
        this.content.Text += "ID:" + i.ItemID + Environment.NewLine;
      this.content.Text += "Key:" + i.ItemKey.ToString() +
            Environment.NewLine;
    }
    stream.Close();
}

2.序列化

private void Write_Click(object sender, EventArgs e)
{
    //初始化类
    PurchaseOrder obj = new PurchaseOrder();
    obj.ItemsOrders = new Item[2];
    obj.ItemsOrders[0] = new Item();
    obj.ItemsOrders[0].ItemID = System.DateTime.Now.ToString();
    obj.ItemsOrders[0].ItemKey = System.DateTime.Now.Ticks;
    obj.ItemsOrders[1] = new Item();
    obj.ItemsOrders[1].ItemID = System.DateTime.Now.AddMonths(2).ToString();
    obj.ItemsOrders[1].ItemKey = System.DateTime.Now.Ticks;
    //创建序列化格式器
    IFormatter formatter = new BinaryFormatter();
    //创建流以保存数据
    Stream stream = new FileStream("MyFile.bin", FileMode.Create,
        FileAccess.Write, FileShare.None);
    //序列化
    formatter.Serialize(stream, obj);
    stream.Close();
    MessageBox.Show("写入结束");
}

3.序列化类

//表示为序列化类
[Serializable]
public class PurchaseOrder
{
    public Item[] ItemsOrders;
}
[Serializable]
public class Item
{
    public string ItemID;
    public decimal ItemKey;
}

3.4 文件的复制与移动

文件的复制和移动在应用软件中十分常见。

范例3-18 批量移动文件

实例位置:光盘\ch03\3-18

范例说明

About the Example

范例将实现将一个文件夹下的所有文件移动到另外一个文件夹中。程序运行效果如图3-25所示。

图3-25 移动文件夹

函数说明

About the Function

1.File.Move(string source,string dest)为移动文件,source为文件的原路径,dest为文件的目标路径。

关键步骤

Key Steps

1.创建新的Windows应用程序。

2.放置控件及移动位置。新建1个FolderBrowserDialog、2个Label及4个Button,并调整位置。

3.其他属性的修改。在属性栏中修改相应控件的属性即可。

4.添加库文件。在代码头部添加“using System.IO;”。

程序代码

Codes

private void start_Click(object sender, EventArgs e)
{
    //获取文件夹的信息
    DirectoryInfo dir = new DirectoryInfo(this.source.Text);
    //获取文件夹下的所有文件
    FileInfo[] Files = dir.GetFiles();
    foreach (FileInfo fi in Files)
    {
          //移动文件
          File.Move(fi.FullName, this.target.Text +"/"+fi.Name);
    }
}

范例3-19 批量移动文件

实例位置:光盘\ch03\3-19

范例说明

About the Example

范例通过将说明如何批量移动文件。程序运行效果如图3-26所示。

图3-26 批量复制文件

函数说明

About the Function

File.Copy(string source,string dest)为复制文件,source为文件的原路径,dest为文件的目标路径。

关键步骤

Key Steps

1.创建新的Windows应用程序。

2.放置控件及移动位置。新建1个FolderBrowserDialog、2个Label及4个Button,并调整位置。

3.其他属性的修改。在属性栏中修改相应控件的属性即可。

程序代码

Codes

private void start_Click(object sender, EventArgs e)
{
    DirectoryInfo dir = new DirectoryInfo(this.sourcestr.Text);
    //获取文件夹下的所有文件
    FileInfo[] Files = dir.GetFiles();
    foreach (FileInfo fi in Files)
    {
        //复制文件
        File.Copy(fi.FullName, this.deststr.Text + "/" + fi.Name);
    }
}

范例3-20 有选择地复制文件

实例位置:光盘\ch03\3-20

范例说明

About the Example

范例说明如何从一个文件夹将符合条件的文件复制到另外一个文件夹。程序运行效果如图3-27所示。

图3-27 有选择的复制文件

函数说明

About the Function

DirectoryInfo. GetFiles(string str)为从目录中获取符合条件的文件,str为文件名需要符合的条件。

关键步骤

Key Steps

1.创建新的Windows应用程序。

2.放置控件及移动位置。新建1个TextBox、2个Label、1个FolderBrowserDialog及4个Button,并调整位置。

3.其他属性的修改。在属性栏中修改相应控件的属性即可。

程序代码

Codes

private void start_Click(object sender, EventArgs e)
{
    DirectoryInfo dir = new DirectoryInfo(this.source.Text);
    //获取文件夹下的所有文件
    FileInfo[] Files = dir.GetFiles(this.conditions.Text);
    foreach (FileInfo fi in Files)
    {
          //复制文件
          File.Copy(fi.FullName, this.dest.Text + "/" + fi.Name);
    }
}

3.5 解密与加密

安全作为现在的一大热门,已经越来越被人们所重视,加密作为安全防护的手段,在软件中也是必不可少的。本节将介绍几种常见的加密类及其使用方法。

范例3-21 文件的加密与解密

实例位置:光盘\ch03\3-21

范例说明

About the Example

范例将说明如何对文件进行加密。程序运行效果如图3-28所示。

图3-28 文件加密

函数说明

About the Function

EncryptFile(string sInputFilename, string sOutputFilename, string sKey)为加密文件,sInputFilename为输入文件路径,sOutputFilename为输出文件路径,sKey为密钥。

关键步骤

Key Steps

1.创建新的Windows应用程序。

2.放置控件及移动位置。新建1个GruopBox、3个Label及3个Button,并调整位置。

3.其他属性的修改。在属性栏中修改相应控件的属性即可。

4.添加库文件。在代码头部添加“using System.IO; using System.Security; using System.Security. Cryptography; using System.Runtime.InteropServices;”。

程序代码

Codes

1.创建密钥

static string GenerateKey()
{
    // 创建一个随机的DESCryptoServiceProvider实例
    DESCryptoServiceProvider desCrypto =
    (DESCryptoServiceProvider)DESCryptoServiceProvider.Create();
    //随机生成key
    return ASCIIEncoding.ASCII.GetString(desCrypto.Key);
}

2.加密文件

static void EncryptFile(string sInputFilename, string sOutputFilename, string sKey)
{
    //在EncryptFile过程中,创建一个输入FileStream对象和一个输出FileStream对象。这
    //些对象可以从目标文件中读取和向其中写入。
    FileStream fsInput = new FileStream(sInputFilename,FileMode.Open,
          FileAccess.Read);
    FileStream fsEncrypted = new FileStream(sOutputFilename,FileMode.Create,
          FileAccess.Write);
    //声明一个DESCryptoServiceProvider类的实例,并初始化。这表示对文件使用的实际加密和
    //解密技术。也可以使用RSAsecurity或另一种加密技术,来创建一个不同的提供程序。
    DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
    DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
    DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
    //创建一个CryptoStream类的实例,方法是:使用加密提供程序获得一个加密对象
    //(CreateEncryptor),并将现有的输出FileStream对象作为构造函数的一部分。
    ICryptoTransform desencrypt = DES.CreateEncryptor();
    CryptoStream cryptostream = new CryptoStream(fsEncrypted,desencrypt,
          CryptoStreamMode.Write);
    //读入输入文件,然后写出到输出文件。传递CryptoStream对象,文件将使用您提供的密钥加
    //密
    byte[] bytearrayinput = new byte[fsInput.Length];
    fsInput.Read(bytearrayinput, 0, bytearrayinput.Length);
      cryptostream.Write(bytearrayinput, 0, bytearrayinput.Length);
      cryptostream.Close();
      fsInput.Close();
      fsEncrypted.Close();
}

范例3-22 文件的解密操作

实例位置:光盘\ch03\3-22

范例说明

About the Example

范例实现了对文件夹的解密功能。程序运行效果如图3-29所示。

图3-29 填充到Excel文件效果

函数说明

About the Function

DecryptFile(string sInputFilename,string sOutputFilename,string sKey)为解密文件,sInputFilename为输入文件路径,sOutputFilename为输出文件路径,sKey为密钥。

关键步骤

Key Steps

1.创建新的Windows应用程序。

2.放置控件及移动位置。新建1个GruopBox、3个Label及3个Button,并调整位置。

3.其他属性的修改。在属性栏中修改相应控件的属性即可。

4.添加库文件。在代码头部添加“using System.IO; using System.Security; using System.Security. Cryptography; using System.Runtime.InteropServices;”。

程序代码

Codes

//解密文件
static void DecryptFile(string sInputFilename,string sOutputFilename,string sKey)
{
    DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
    //获取密钥
    DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
    DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
    //创建流以读取文件
    FileStream fsread = new FileStream(sInputFilename,FileMode.Open,
          FileAccess.Read);
    //创建翻译器
    ICryptoTransform desdecrypt = DES.CreateDecryptor();
    //创建流以翻译读取的数据
    CryptoStream cryptostreamDecr = new CryptoStream(fsread,desdecrypt,
          CryptoStreamMode.Read);
    //写入文件
    StreamWriter fsDecrypted = new StreamWriter(sOutputFilename);
    fsDecrypted.Write(new StreamReader(cryptostreamDecr).ReadToEnd());
    fsDecrypted.Flush();
    fsDecrypted.Close();
}

范例3-23 加密算法(1)

实例位置:光盘\ch03\3-23

范例说明

About the Example

范例将介绍常用的加密算法。

函数说明

About the Function

DSACryptoServiceProvider.SignData(string str)为加密字符串,返回一个数组。str为待加密字符串。

关键步骤

Key Steps

1.创建新的控制台应用程序。

2.添加库文件。在代码头部添加“using System;using System.Text;using System.Security.Cryptography; ”。

程序代码

Codes

String str = "this is a test.";
byte[] bytes = Encoding.ASCII.GetBytes(str);
//选择签名方式DSA
DSACryptoServiceProvider dsac = new DSACryptoServiceProvider();
//签名结果
byte[] sign = dsac.SignData(bytes);
//加密认证
DSACryptoServiceProvider dsac2 = new DSACryptoServiceProvider();
dsac2.FromXmlString(dsac.ToXmlString(false));
bool ver = dsac2.VerifyData(bytes, sign);
if (ver)
{
    Console.WriteLine("通过");
}
else
{
      Console.WriteLine("不能通过");
}

范例3-24 加密算法(2)

实例位置:光盘\ch03\3-24

范例说明

About the Example

范例将介绍常用的加密算法。

函数说明

About the Function

RSACryptoServiceProvider.SignData(byte [] data,int offset,int len,SHA1CryptoServiceProvider hash) data为待加密的数据,offset为偏移量,len为选取的key长度,hash为提供哈希值的SHA1CryptoServiceProvider实例。

关键步骤

Key Steps

1.创建新的控制台应用程序。

2.添加库文件。在代码头部添加“using System;using System.Text;using System.Security.Cryptography;”。

程序代码

Codes

//创建转换器,将string变为数组
ASCIIEncoding ByteConverter = new ASCIIEncoding();
string dataString = "Data to Sign";
//创建数组以保存信息
byte[] originalData = ByteConverter.GetBytes(dataString);
byte[] signedData;
byte[] smallArray;
//创建RSACryptoServiceProvider实例,并自动创建key
RSACryptoServiceProvider RSAalg = new RSACryptoServiceProvider();
// 将key的信息赋给RSAParameters对象.
// 私有密钥参数必须填true
RSAParameters Key = RSAalg.ExportParameters(true);
// 加密数据,只用key的偏移为5的7个长度的数据
signedData = HashAndSignBytes(originalData, Key, 5, 7);
//记录使用的密钥,偏移5的7个长度的数据
smallArray = new byte[7];
Array.Copy(originalData, 5, smallArray, 0, 7);
//验证
if (VerifySignedHash(smallArray, signedData, Key))
{
      Console.WriteLine("通过");
}
else
{
      Console.WriteLine("不能通过");
}

范例3-25 加密算法(3)

实例位置:光盘\ch03\3-25

范例说明

About the Example

范例将介绍常用的加密算法。

函数说明

About the Function

DSACryptoServiceProvider.SignData(string str)为加密字符串,返回一个数组。str为待加密字符串。

关键步骤

Key Steps

1.创建新的控制台应用程序。

2.添加库文件。在代码头部添加“using System;using System.Text;using System.Security.Cryptography; ”。

程序代码

Codes

static string getMd5Hash(string input)
{
    //创建MD5CryptoServiceProvider实例
    MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider();
    //将字符串转换为数组并计算hash值
    byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input));
    //创建StringBuilder来生成string
    StringBuilder sBuilder = new StringBuilder()
    //将数组的每个值转化为hexadecimal string.
    for (int i = 0; i < data.Length; i++)
    {
          sBuilder.Append(data[i].ToString("x2"));
    }
    //返回hexadecimal string.
    return sBuilder.ToString();
}
// 验证hash值和字符串是否匹配
static bool verifyMd5Hash(string input, string hash)
{
    //获取输入字符串的hash值
    string hashOfInput = getMd5Hash(input);
    //创建一个StringComparer实例
    StringComparer comparer = StringComparer.OrdinalIgnoreCase;
    if (0 == comparer.Compare(hashOfInput, hash))
    {
          return true;
    }
    else
    {
          return false;
    }
}

3.6 文件目录

目录管理是现在主流的文件管理方式,文件目录的重要性毋庸置疑。本节将介绍关于目录的各种操作。

范例3-26 新建文件夹

实例位置:光盘\ch03\3-26

范例说明

About the Example

范例将根据用户输入的路径来建立一个新的文件夹。程序运行效果如图3-30所示。

图3-30 新建文件夹

函数说明

About the Function

Directory.CreateDirectory(string path)为创建该路径包含的文件夹并返回DirectoryInfo,path为待创建的路径。

关键步骤

Key Steps

1.创建新的Windows工程。

2.放置控件及移动位置。新建1个TextBox、1个Label、1个FolderBrowserDialog及1个Button,并调整位置。

3.其他属性的修改。在属性栏中修改相应控件的属性即可。

4.添加库文件。在代码头部添加“using System.IO”。

程序代码

Codes

private void create_Click(object sender, EventArgs e)
{
    if (!Directory.Exists(path.Text))
          //创建文件夹
          Directory.CreateDirectory(path.Text);
    else
          MessageBox.Show("该路径已经存在");
}

范例3-27 修改文件架名称

实例位置:光盘\ch03\3-27

范例说明

About the Example

范例通过用户输入的路径和名称来修改指定路径的文件夹的名称。程序运行效果如图3-31所示。

图3-31 修改文件夹名称

函数说明

About the Function

Directory.Move(string source,string dest)为移动文件夹,source为源文件夹位置,dest为目标文件夹位置。

关键步骤

Key Steps

1.创建新的工程。

2.放置控件及移动位置。新建2个TextBox、2个Label、1个FolderBrowserDialog及2个Button,并调整位置。

3.其他属性的修改。在属性栏中修改相应控件的属性即可。

4.添加库文件。在代码头部添加“using System.IO;”。

程序代码

Codes

private void Modify_Click(object sender, EventArgs e)
{
    string mpath = this.path.Text.Remove(this.path.Text.LastIndexOf(@"\") + 1)
                    + this.name.Text;
    //移动文件夹
    Directory.Move(this.path.Text, mpath);
    MessageBox.Show("修改结束");
}

范例3-28 读取和设置文件夹的属性

实例位置:光盘\ch03\3-28

范例说明

About the Example

范例讲解如何读取和设置文件夹的属性。程序运行效果如图3-32所示。

图3-32 读取和设置文件夹属性

关键步骤

Key Steps

1.创建新的Windows工程。

2.放置控件及移动位置。新建1个TextBox、1个Label、1个FolderBrowserDialog、2个CheckBox及2个Button,并调整位置。

3.其他属性的修改。在属性栏中修改相应控件的属性即可。

4.添加库文件。在代码头部添加“using System.IO;”。

程序代码

Codes

private void View_Click(object sender, EventArgs e)
{
    this.folderBrowserDialog1.ShowDialog();
    this.path.Text = this.folderBrowserDialog1.SelectedPath;
    //获取路径信息
    System.IO.DirectoryInfo dic = new DirectoryInfo(path.Text);
    //转化为字符串形式
    string dicAttributes = dic.Attributes.ToString();
    //判断是否只读
    if (dicAttributes.IndexOf("ReadOnly") != -1)
          this.read.Checked = true;
    else
          this.read.Checked = false;
    //判断是否隐藏
    if (dicAttributes.IndexOf("Hidden") != -1)
        this.hide.Checked = true;
    else
        this.hide.Checked = false;
}
private void Modify_Click(object sender, EventArgs e)
{
    System.IO.DirectoryInfo dic = new DirectoryInfo(path.Text);
    //将文件夹属性置空
    dic.Attributes=FileAttributes.Directory;
    //如果CheckBox打钩,则添加相应属性
    if (this.read.Checked == true)
        dic.Attributes = dic.Attributes | FileAttributes.ReadOnly;
    if (this.hide.Checked == true)
        dic.Attributes = dic.Attributes | FileAttributes.Hidden;
}

范例3-29 个性化文件夹背景

实例位置:光盘\ch03\3-29

范例说明

About the Example

范例将根据用户选择的路径和图片来更换该文件夹的背景图片。程序运行效果如图3-33所示。

图3-33 个性化文件夹效果

关键步骤

Key Steps

1.创建新的Windows工程。

2.放置控件及移动位置。新建2个TextBox、2个Label、1个OpenFileDialog及4个Button,并调整位置。

3.其他属性的修改。在属性栏中修改相应控件的属性即可(这里修改Text属性)。

4.添加库文件。在代码头部添加“using System.IO;”。

程序代码

Codes

1.设置为个性化

private void Modify_Click(object sender, EventArgs e)
{
    string hostName =
    System.Reflection.Assembly.GetExecutingAssembly().Location;
          hostName =hostName.Substring(0, hostName.LastIndexOf('\\'));
    //将配置文件复制到目标文件夹
    File.Copy(hostName + @"\desktop.ini", this.dic.Text + @"\desktop.ini");
    //设置为隐藏
    File.SetAttributes(this.dic.Text + @"\desktop.ini", FileAttributes.Hidden);
    //将图片文件复制到目标文件夹
    File.Copy(this.pic.Text, this.dic.Text + @"\pic.jpg");
    //设置为隐藏
    File.SetAttributes(this.dic.Text + @"\pic.jpg", FileAttributes.Hidden);
}

2.还原文件夹

private void Recover_Click(object sender, EventArgs e)
{
    //删除相应的文件
    File.Delete(this.dic.Text + @"\desktop.ini");
    File.Delete(this.dic.Text + @"\pic.jpg");
}

范例3-30 删除文件夹

实例位置:光盘\ch03\3-30

范例说明

About the Example

范例通过删除用户指定路径的文件夹介绍删除文件夹的函数及用法。程序运行效果如图3-34所示。

图3-34 删除文件夹

函数说明

About the Function

Directory.Delete(string path,bool flag)为删除文件夹,path为文件夹路径,flag为是否删除子文件夹。

关键步骤

Key Steps

1.创建新的Windows工程。

2.放置控件及移动位置。新建1个TextBox、1个Label、1个FolderBrowserDialog及2个Button,并调整位置。

3.其他属性的修改。在属性栏中修改相应控件的属性即可。

4.添加库文件。在代码头部添加“using System.IO;”。

程序代码

Codes

//删除指定的路径,以及下面的所有文件与子文件夹
Directory.Delete(this.path.Text, true);

范例3-31 获取指定文件夹下的所有文件

实例位置:光盘\ch03\3-31

范例说明

About the Example

范例通过获取用户指定的目录下的文件来说明对目录和文件的操作。程序运行效果如图3-35所示。

图3-35 填充到Excel文件效果

函数说明

About the Function

Directory.GetFiles(string str); 为返回该目录中符合条件的文件的文件名字符数组,str为目录路径。

关键步骤

Key Steps

1.创建新的Windows工程。

2.放置控件及移动位置。新建1个TextBox、2个Label、1个ListView、1个FolderBrowserDialog及2个Button,并调整位置。

3.其他属性的修改。在属性栏中修改相应控件的属性即可。

4.添加库文件。在代码头部添加“using System.IO;”。

程序代码

Codes

private void button2_Click(object sender, System.EventArgs e)
{   //显示指定文件夹下的文件
    if(this.textBox1.Text.Trim()=="")
          return;
    this.listBox1.Items.Clear();
    //获取目录下的文件
    string[] MyFiles=Directory.GetFiles(this.textBox1.Text);
    this.listBox1.Items.AddRange(MyFiles);
}

范例3-32 获取当前程序所在路径

实例位置:光盘\ch03\3-32

范例说明

About the Example

范例将介绍获取当前程序的工作目录,该目录的作用很多。程序运行效果如图3-36所示。

图3-36 获取当前程序所在文件夹

函数说明

About the Function

Directory.GetCurrentDirectory()为获取当前程序的工作目录。

关键步骤

Key Steps

1.创建新的工程。

2.放置控件及移动位置。新建1个RichTextBox、1个Label及1个Button、1个FolderBrowserDialog,并调整位置。

3.其他属性的修改。在属性栏中修改相应控件的属性即可(这里修改Text属性)。

4.添加库文件。在代码头部添加“using System.IO;”。

程序代码

Codes

this.path.Text+="当前执行程序所在的文件夹为:" +Environment.NewLine+
Directory.GetCurrentDirectory();

范例3-33 获取指定文件夹下的所有文件夹

实例位置:光盘\ch03\3-33

范例说明

About the Example

范例通过获取用户指定的文件夹下的所有子文件夹来说明如何对文件夹进行操作。程序运行效果如图3-37所示。

图3-37 显示子目录

函数说明

About the Function

Directory.GetDirectories(string path)为获取文件夹下的字文件夹并以字符数组返回,path为文件夹路径。

关键步骤

Key Steps

1.创建新的工程。

2.放置控件及移动位置。新建1个TextBox、2个Label、1个FolderBrowserDialog及2个Button,并调整位置。

3.其他属性的修改。在属性栏中修改相应控件的属性即可。

4.添加库文件。在代码头部添加“using System.IO;”。

程序代码

Codes

private void button2_Click(object sender, System.EventArgs e)
{//显示指定文件夹下的子文件夹
    if(this.textBox1.Text.Trim()=="")
          return;
    this.listBox1.Items.Clear();
    //获取指定文件夹下的所有子文件夹
    string[] MyFolders=Directory.GetDirectories(this.textBox1.Text);
              this.listBox1.Items.AddRange(MyFolders);
}

范例3-34 删除和创造多层文件夹

实例位置:光盘\ch03\3-34

范例说明

About the Example

范例通过创建和删除用户指定的多层路径来说明对文件夹的操作。程序运行效果如图3-38所示。

图3-38 删除创建多层文件夹

关键步骤

Key Steps

1.创建新的工程。

2.放置控件及移动位置。新建2个TextBox、2个Label、1个FolderBrowserDialog及4个Button,并调整位置。

3.其他属性的修改。在属性栏中修改相应控件的属性即可。

4.添加库文件。在代码头部添加“using System.IO;”。

程序代码

Codes

private void button3_Click(object sender, System.EventArgs e)
{//删除文件夹
    if(this.textBox1.Text.Trim()=="")
          return;
    DirectoryInfo MyDir=new DirectoryInfo(this.textBox1.Text);
    if(MessageBox.Show("是否删除文件夹:"+this.textBox1.Text+"及其所有内容?","信息提
     示",MessageBoxButtons.YesNo,MessageBoxIcon.Question)==DialogResult.Yes)
    {
        MyDir.Delete(true);
        this.textBox1.Text="";
    }
}
private void button2_Click(object sender, System.EventArgs e)
{//创建多层文件夹
    if(this.textBox2.Text.Trim()=="")
        return;
    if(Directory.Exists(this.textBox2.Text))
    {
        MessageBox.Show("该文件夹已经存在!","信息提示
        ",MessageBoxButtons.OK,MessageBoxIcon.Information);
        return;
    }
    if(MessageBox.Show("是否创建多层文件夹:"+this.textBox2.Text,"信息提示
        ",MessageBoxButtons.YesNo,MessageBoxIcon.Question)==DialogResult.Yes)
    {
        Directory.CreateDirectory(this.textBox2.Text);
        this.textBox2.Text="";
    }
}

范例3-35 监视文件夹的变化情况

实例位置:光盘\ch03\3-35

范例说明

About the Example

范例将通过FileSystemWatcher来监视文件夹的变化情况。程序运行效果如图3-39和图3-40所示。

图3-39 进入FileSystemWatcher的事件页

图3-40 监视文件夹变化

函数说明

About the Function

FileSystemEventArgs.FullPath

FullPath是FileSystemEventArgs的属性,标记发出事件的对象的路径。

关键步骤

Key Steps

1.创建新的工程。

2.放置控件及移动位置。新建2个TextBox、2个Label、1个FolderBrowserDialog、1个FileSystemWatcher及1个Button,并调整位置。

3.其他属性的修改。在属性栏中修改相应控件的属性即可。

4.添加库文件。在代码头部添加“using System.IO;”。

5.为FileSystemWatcher的事件添加响应函数。首先,单击FileSystemWatcher的属性页,然后单击,进入事件页,如图3-39所示。然后,双击事件后的空白处,系统会自动添加对该事件的监视,并添加相应的响应函数。FileSystemWatcher有4个事件,分别是Changed、Renamed、Create及Deleted。最后,在响应函数中加入需要的操作即可。

程序代码

Codes

private void button1_Click_1(object sender, System.EventArgs e)
{   //浏览文件夹
    this.folderBrowserDialog1.ShowDialog();
    this.folderBrowserDialog1.SelectedPath;
    this.fileSystemWatcher1.Path = this.textBox1.Text;
    MessageBox.Show(this.textBox1.Text + "已经处于被监视状态!");
}
private void fileSystemWatcher1_Changed(object sender, FileSystemEventArgs e)
{   //发生改变
    this.richTextBox1.Text+=e.FullPath.ToString()+"  发生改变!\n";
}
private void fileSystemWatcher1_Created(object sender, FileSystemEventArgs e)
{   //新增
    this.richTextBox1.Text += "新增:" + e.FullPath.ToString() + "\n";
}
private void fileSystemWatcher1_Deleted(object sender, FileSystemEventArgs e)
{   //删除
    this.richTextBox1.Text += "删除:" + e.FullPath.ToString() + "\n";
}
private void fileSystemWatcher1_Renamed(object sender, RenamedEventArgs e)
{   //更名
    this.richTextBox1.Text += "更名:" + e.FullPath.ToString() + "\n";
}

范例3-36 个性化文件夹图标

实例位置:光盘\ch03\3-36

范例说明

About the Example

范例实现了对文件夹图标的更改。程序运行效果如图3-41所示。

图3-41 个性化文件夹图标

关键步骤

Key Steps

1.创建新的工程。

2.放置控件及移动位置。新建1个TextBox、1个Label、1个OpenFileDialog及2个Button,并调整位置。

3.其他属性的修改。在属性栏中修改相应控件的属性即可。

4.添加库文件。在代码头部添加“using System.IO;”。

程序代码

Codes

private void Modify_Click(object sender, EventArgs e)
{
    string hostName = System.Reflection.Assembly.
                            GetExecutingAssembly().Location ;
    hostName =hostName.Substring(0, hostName.LastIndexOf('\\'));
    \\配置文件已经存在则删除
    if (File.Exists(this.dic.Text + @"\desktop.ini"))
    {
          File.Delete(this.dic.Text + @"\desktop.ini");
    }
    \\复制配置文件到目标文件夹
    File.Copy(hostName + @"\desktop.ini", this.dic.Text + @"\desktop.ini");
    File.SetAttributes(this.dic.Text + @"\desktop.ini", FileAttributes.Hidden);
}

3.7 文件的修改与删除

范例3-37 删除指定文件

实例位置:光盘\ch03\3-37

范例说明

About the Example

范例通过删除用户指定的路径上的文件来说明如何删除文件。程序运行效果如图3-42所示。

图3-42 填充到Excel文件效果

函数说明

About the Function

File.Delete(stirng path)为删除指定路径的文件,path为待删除文件的路径。

关键步骤

Key Steps

1.创建新的工程。

2.放置控件及移动位置。新建1个TextBox、1个Label、1个FolderBrowserDialog及2个Button,并调整位置。

3.其他属性的修改。在属性栏中修改相应控件的属性即可。

4.添加库文件。在代码头部添加“using System.IO;”。

程序代码

Codes

//删除指定路径的文件
File.Delete(this.path.Text);

范例3-38 批量删除文件

实例位置:光盘\ch03\3-38

范例说明

About the Example

范例将删除指定目录中包含特定后缀的文件来说明如何批量删除文件。程序运行效果如图3-43所示。

图3-43 批量删除文件

函数说明

About the Function

DirectoryInfo.GetFiles(string pattern, SearchOption searchOption)为获取目录下的文件列表,pattern为文件的后缀,searchOption是否查找子自文件夹。

关键步骤

Key Steps

1.创建新的工程。

2.放置控件及移动位置。新建2个TextBox、2个Label、1个FolderBrowserDialog及2个Button,并调整位置。

3.其他属性的修改。在属性栏中修改相应控件的属性即可。

4.添加库文件。在代码头部添加“using System.IO;”。

程序代码

Codes

private void delete_Click(object sender, EventArgs e)
{
    DirectoryInfo di = new DirectoryInfo(this.path.Text);
    //获取符合条件的文件
    FileInfo [] files = di.GetFiles(this.con.Text, SearchOption.AllDirectories);
    //循环删除
    foreach (FileInfo fi in files)
          fi.Delete();
}

范例3-39 重命名文件

实例位置:光盘\ch03\3-39

范例说明

About the Example

范例实现了重命名文件的功能。程序运行效果如图3-44所示。

图3-44 填充到Excel文件效果

函数说明

About the Function

File.Move(string source,string dest)为移动文件,source为文件的原路径,dest为文件的目标路径。

关键步骤

Key Steps

1.创建新的工程。

2.放置控件及移动位置。新建1个RichTextBox、1个Label及1个Button,并调整位置。

3.其他属性的修改。在属性栏中修改相应控件的属性即可。

4.添加库文件。在代码头部添加“using System.IO;”。

程序代码

Codes

private void modify_Click(object sender, EventArgs e)
{
    string sname=this.path.Text.Substring(this.path.Text.LastIndexOf(@"\")+1,
          this.path.Text.LastIndexOf(".")-this.path.Text.LastIndexOf(@"\")-1);
    string npath = this.path.Text.Substring(0, this.path.Text.LastIndexOf(@"\")
          +1) + this.path.Text.Substring(this.path.Text.LastIndexOf(@"\") + 1).
          Replace(sname, this.name.Text);
    File.Move(this.path.Text,npath);
}

范例3-40 文件关联

实例位置:光盘\ch03\3-40

范例说明

About the Example

范例实现了在操作系统中将.gl后缀文件的打开方式设置为本程序,来说明如何对文件关联进行操作。使用时先双击EXE,这样建立起.gl文件和程序间的关联,然后双击.gl后缀的文件,系统会自动使用本程序打开。程序运行效果如图3-45所示。

图3-45 打开.gl后缀文件

关键步骤

Key Steps

1.创建新的工程。

2.放置控件及移动位置。新建1个RichTextBox,并调整位置。

3.对启动文件进行修改。由于要接受.gl文件的内容,所以Main函数带参数,先在解决方案资源管理器中找到Program.cs,然后将Main()部分修改为:

static void Main(string[] args)
{
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    Application.Run(new Form1(args));
}

4.对构造函数进行修改。将public Form1()变为public Form1(string[] args),来接受文件的数据。

5.添加库文件。在代码头部添加“using Microsoft.Win32;”。

程序代码

Codes

public Form1(string[] args)
{
    //如果无参数,则进行关联,如果有参数,则初始化控件
    if (args.Length != 0)
    {
          strFile = args[0];
          InitializeComponent();
    }
    else
    {
          string FileExt;
          string FileType;
          string MIMEType;
          string ExecName;
          FileExt = ".gl";
          FileType = "关联";
          MIMEType = "text/plain";
          ExecName = Application.ExecutablePath + " %1";
          RegistryKey RegKey;
          RegKey = Registry.ClassesRoot;
          RegKey = RegKey.CreateSubKey(FileExt);
          RegKey.SetValue("", FileType);
          RegKey.SetValue("Content Type", MIMEType);
          RegKey = RegKey.CreateSubKey("shell\\open\\command");
          RegKey.SetValue("", ExecName);
          RegKey.Close();
    }
}
private void Form1_Load(object sender, EventArgs e)
{
    //显示文件参数
    this.richTextBox.LoadFile(strFile, RichTextBoxStreamType.PlainText);
}

3.8 其他

范例3-41 获取磁盘空间信息

实例位置:光盘\ch03\3-41

范例说明

About the Example

范例通过获取C盘的总空间和剩余空间来说明如何获取磁盘的空间信息。程序运行效果如图3-46所示。

图3-46 获取磁盘空间信息

函数说明

About the Function

ManagementObject.Get()为获取被管理对象的信息。

关键步骤

Key Steps

1.创建新的工程。

2.放置控件及移动位置。新建1个Label并调整位置。

3.其他属性的修改。在属性栏中修改相应控件的属性即可。

4.添加引用。在解决方案资源管理器的引用项上单击鼠标右键,选择添加引用,然后在.Net标签页中找到System.Management,并单击【添加】按钮。

5.添加库文件。在代码头部添加“using System.Management”。

程序代码

Codes

private void Form1_Load(object sender, EventArgs e)
{
    //创建ManagementObject对象,注意这里的初始化字符的格式
    ManagementObject disk = new ManagementObject
          ("win32_logicaldisk.deviceid=\"c:\"");
    disk.Get();
    this.space.Text += "\nc盘磁盘空间信息:\n";
    this.space.Text+="Logical Disk Size = " + disk["Size"] + " bytes\n";
    this.space.Text+="Logical Disk FreeSpace = " + disk["FreeSpace"] + " bytes";
}

范例3-42 获取指定文件图标

实例位置:光盘\ch03\3-42

范例说明

About the Example

实例实现了获取用户指定文件的图标功能。程序运行效果如图3-47所示。

图3-47 填充到Excel文件效果

关键步骤

Key Steps

1.创建新的工程。

2.放置控件及移动位置。新建1个TextBox、1个Label、1个OpenFileDialog、1个PictrueBox及1个Button,并调整位置。

3.其他属性的修改。在属性栏中修改相应控件的属性即可。

程序代码

Codes

        private void view_Click(object sender, EventArgs e)
        {
            this.openFileDialog1.ShowDialog();
            this.path.Text = this.openFileDialog1.FileName;
            icon = Files.IconReader.GetFileIcon(this.path.Text,
            Files.IconReader.IconSize.Small, true);
            this.pictureBox1.Image = icon.ToBitmap();
        }

范例3-43 压缩与解压缩文件

实例位置:光盘\ch03\3-43

范例说明

About the Example

范例实现对文件的压缩和解压功能。程序运行效果如图3-48所示。

图3-48 填充到Excel文件效果

函数说明

About the Function

1.GZipStream.Read(byte [] buf,int offset,int count)为读取压缩过的数据,buf为接受数据的数组,offset为读取的偏移量,一般为0,count为读取的长度。

2.GZipStream.Write(byte [] buf,int offset,int count)为写入压缩的数据,buf为接受数据的数组,offset为读取的偏移量,一般为0,count为读取的长度。

关键步骤

Key Steps

1.创建新的工程。

2.放置控件及移动位置。新建2个TextBox、2个Label及4个Button,并调整位置。

3.其他属性的修改。在属性栏中修改相应控件的属性即可。

4.添加库文件。在代码头部添加“using System.IO;using System.IO.Compression;”。

程序代码

Codes

1.压缩文件

public void CompressFile(string sourceFile, string destinationFile)
{
    // 确保文件存在
    if (File.Exists(sourceFile) == false)
          throw new FileNotFoundException();
    // 创建所需的数据结构
    byte[] buffer = null;
    FileStream sourceStream = null;
    FileStream destinationStream = null;
    GZipStream compressedStream = null;
    try
    {
          //读取数据
          sourceStream = new FileStream(sourceFile, FileMode.Open,
                            FileAccess.Read, FileShare.Read);
          buffer = new byte[sourceStream.Length];
          int checkCounter = sourceStream.Read(buffer, 0, buffer.Length);
          if (checkCounter != buffer.Length)
          {
              throw new ApplicationException();
          }
          //写入数据
          destinationStream = new FileStream(destinationFile,
                            FileMode.OpenOrCreate, FileAccess.Write);
          //创建压缩流
          compressedStream = new GZipStream(destinationStream,
                            CompressionMode.Compress, true);
          //通过压缩流写数据
          compressedStream.Write(buffer, 0, buffer.Length);
    }
    catch (ApplicationException ex)
    {
          MessageBox.Show(ex.Message, "压缩文件时发生错误:", MessageBoxButtons.OK,
                      MessageBoxIcon.Error);
    }
    finally
    {
          //关闭所有打开的流
          if (sourceStream != null)
              sourceStream.Close();
          if (compressedStream != null)
              compressedStream.Close();
          if (destinationStream != null)
              destinationStream.Close();
    }
}

2.解压缩文件

public void DecompressFile(string sourceFile, string destinationFile)
{
    //确保文件存在
    if (File.Exists(sourceFile) == false)
        throw new FileNotFoundException();
    // 创建所需的数据结构
    FileStream sourceStream = null;
    FileStream destinationStream = null;
    GZipStream decompressedStream = null;
    byte[] quartetBuffer = null;
    try
    {
        //读取压缩过的数据
        sourceStream = new FileStream(sourceFile, FileMode.Open);
        //创建压缩流
        decompressedStream = new GZipStream(sourceStream,
          CompressionMode.Decompress, true);
        //读取数据
        quartetBuffer = new byte[4];
        int position = (int)sourceStream.Length -4;
        sourceStream.Position = position;
        sourceStream.Read(quartetBuffer, 0, 4);
        sourceStream.Position = 0;
        int checkLength = BitConverter.ToInt32(quartetBuffer, 0);
        byte[] buffer = new byte[checkLength + 100];
        int offset = 0;
        int total = 0;
        while (true)
        {
              int bytesRead = decompressedStream.Read(buffer, offset, 100);
              if (bytesRead == 0)
                  break;
              offset += bytesRead;
              total += bytesRead;
        }
        //写入目标文件
        destinationStream = new FileStream(destinationFile, FileMode.Create);
        destinationStream.Write(buffer, 0, total);
        //清理内存
        destinationStream.Flush();
    }
    catch (ApplicationException ex)
    {
        MessageBox.Show(ex.Message, "解压文件时发生错误:", MessageBoxButtons.OK,
        MessageBoxIcon.Error);
    }
    finally
    {
        //关闭所有流
    if (sourceStream != null)
        sourceStream.Close();
    if (decompressedStream != null)
        decompressedStream.Close();
    if (destinationStream != null)
        destinationStream.Close();
    }
}

范例3-44 程序实例唯一化

实例位置:光盘\ch03\3-44

范例说明

About the Example

范例主要讲述如何进行磁盘整理。

函数说明

About the Function

Process.GetProcessesByName(string fileName)通过名称获取进程,返回一个进程数组,fileName为进程名称。

关键步骤

Key Steps

1.创建新的工程。

2.在Main()函数种加入相应的代码。

程序代码

Codes

static void Main()
{
    System.Diagnostics.Process[] pApp =
    System.Diagnostics.Process.GetProcessesByName("Files");
    //如果已经存在1个进程,则返回,否则构造程序
    if (pApp.Length > 1)
    {
          return;
    }
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    Application.Run(new Form1());
}

范例3-45 剪贴板

实例位置:光盘\ch03\3-45

范例说明

About the Example

范例实现了循化剪贴板的功能。如图3-49所示。

图3-49 剪贴板

函数说明

About the Function

1.Clipboard.GetDataObject()获取剪贴板中的数据,返回一个IDataObject

2.Clipboard.SetDataObject(object o)设置剪贴板数据,o为数据内容。

3.Clipboard.GetDataPresent(Type format)为是否可将剪贴板的数据转换为指定格式,返回bool,Format为数据格式。

关键步骤

Key Steps

1.创建新的工程。

2.放置控件及移动位置。新建1个ToolBar、1个RichTextBox及1个ContentMenu,并调整位置。

3.其他属性的修改。在属性栏中修改相应控件的属性即可。

程序代码

1.初始化第一个菜单项

Codes

MenuItem newItem = new MenuItem("文本:" + s);
if (s.Length > 15)
{
    newItem.Text = "文本:" + s.Substring(0, 15) + "...";
}
newItem.Click += new EventHandler(menuItemClick);
this.contextMenu1.MenuItems.Add(newItem);
this.contextMenu1.MenuItems[0].Text = "文本:" + s;
this.clipboardText[0] = s;

2.菜单项事件处理

private void menuItemClick(object sender, System.EventArgs e)
{
    //获取发出信息的菜单项
    MenuItem mItem = (MenuItem)sender;
    //获得菜单项索引
    int i = mItem.Index;
    //放到剪贴板
    Clipboard.SetDataObject(this.clipboardText[i]);
    //复制它到richTextBox上
    this.richTextBox1.Paste();
}

3.实现【粘贴】按钮的功能

if (e.Button == this.toolBarButton3)
{
    try
    {
          IDataObject d = Clipboard.GetDataObject();
          //判断剪贴板中数据是不是文本
          if (d.GetDataPresent(DataFormats.UnicodeText))
          {
              //将文本对象粘贴到文本框里面
              this.richTextBox1.Paste();
          }
          else
          {
              //如果剪贴板上没有文本,则发出提醒
              MessageBox.Show("没有可粘贴的文本", "提示", MessageBoxButtons.OK,
                MessageBoxIcon.Exclamation);
          }
    }
    catch (Exception error)
    {
          //读取剪贴板出错处理
          MessageBox.Show("错误信息是: " + error.Message, "错误",
          MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

范例3-46 获取系统可用驱动器列表

实例位置:光盘\ch03\3-46

范例说明

About the Example

范例通过System.Environment来获取系统中可用的驱动器列表。程序运行效果如图3-50所示。

图3-50 填充到Excel文件效果

关键步骤

Key Steps

1.创建新的工程。

2.放置控件及移动位置。新建1个Label,并调整位置。

3.增加响应事件。添加对Form_Load事件的监视,并增加响应函数。

程序代码

Codes

private void Form1_Load(object sender, EventArgs e)
{
    drives = Environment.GetLogicalDrives();
    for (int i = 0; i < drives.Length; i++)
    {
          string str_temp = drives[i];
          this.driver.Text += "\n"+str_temp;
    }
}

3.9 本章小结

文件是数据存储的手段,使用电脑是操作文件的过程。本章内容大体囊括了常用的文件操作,请读者多加练习。