最近写了一个小程序,学了不少东西,总结一下,要实现的功能是读取本地文件夹中的txt和png文件自动生成一个.docx报告文档,首先对需要解决的问题进行分解,最后组合起来。
1.打开一个本地文件夹,利用IO命名空间中的目录信息DirectoryInfo的GetFiles方法获得该目录中文件列表,然后根据扩展名判断是否同时包含txt和png文件,如果是,则将目录信息作为参数进行传递并显示在两个文本框中,以便后期操作,否则重新选择文件夹。参考博客http://www.cnblogs.com/skylaugh/archive/2012/09/23/2698850.html
private void PathBtn_Click(object sender, EventArgs e)
{
this.GenerateReportBtn.Enabled = true ;
this.toolStripStatusLabel1.Text = "正在打开文件...";
FolderBrowserDialog folderDLg = new FolderBrowserDialog();
folderDLg.Description = "打开生成报告文件目录";
string folderName;
folderDLg.ShowDialog();
folderName = folderDLg.SelectedPath;
if (folderName == "")
{
MessageBox.Show("结果目录不能为空,请选择指定目录","提示",MessageBoxButtons.OK,MessageBoxIcon.Warning);
return;
}
DirectoryInfo directory = new DirectoryInfo(folderName);
FileInfo[] filesInfo = directory.GetFiles();
int length = filesInfo.Length;
int count = 0;
foreach (FileInfo NextFile in directory.GetFiles())
{
string fileExtension = NextFile.Extension;
switch (fileExtension)
{
case ".txt":
count++;
break;
case ".png":
count++;
break;
case ".docx":
count++;
break;
}
}
if (count == length)
{
OperateWord operateWord = new OperateWord();
operateWord.FolderName = folderName;
this.WordDocTxtBox.Text = folderName;
this.DocxSaveAsTxtBox.Text = operateWord.GetWordFullName();
}
else
{
MessageBox.Show("指定文件夹中没有txt文件和png图片,请重新选择!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
this.toolStripStatusLabel1.Text = "打开文件路径成功";
}
2.打开包含txt和png文件的目录后,需要根据文件的扩展名分别将txt和png文件的文件名和目录信息存放在四个字符串数组中,以便后期使用,这一步需要解决两个问题:一是统计字符串中某个字符出现的次数,并去掉不符合要求的txt文件;二是需要对含有数字的的字符串根据数字进行排序。参考博客http://q.cnblogs.com/q/54877/ 和http://q.cnblogs.com/q/54877/
DirectoryInfo directory = new DirectoryInfo(folderName);
List<string> txtList = new List<string>();
List<string> pngList = new List<string>();
List<string> txtListPath = new List<string>(