1.编写C#程序,统计硬盘某个目录下的abc.txt文本文件中单词的个数。提示:要用到字符串类中的分割字符串等函数。
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
namespace exc11
{
class Program
{
static void Main(string[] args)
{
string fileSrc = "D:\\abc.txt";
string words = "";
if (!File.Exists(@fileSrc))
Console.WriteLine("文件" + @fileSrc + "不存在");
else
{
int a;
FileStream fs = new FileStream(@fileSrc, FileMode.Open, FileAccess.Read);
a = fs.ReadByte();
while (a != -1) //是否读到文件末尾
{
words+= ((char)a).ToString();
a = fs.ReadByte();
}
Console.Write("原文" + words);
Console.WriteLine();
int Count = words.Split(' ').Length; //使用split()、Length。
Console.WriteLine("单词个数:" + Count.ToString());
Console.Read();
fs.Close();
}
}
}
}
运行结果:
2.编写一个重复文件的检测程序:程序可以实现重复文件检测(即将硬盘某个盘符下的重复文件以ListBox控件列表的形式显示出来,例如:有1.doc、2.doc、3.doc完全一样,则这三个应该放在同一个ListBox1控件中;而a.exe、b.exe完全一样,则放在另一个ListBox2控件中)。
实现代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace exc11_2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
StartPosition = FormStartPosition.CenterScreen;
}
private void button1_Click(object sender, EventArgs e)
{
List<FileInfo> lst = new List<FileInfo>();
List<FileInfo> lst1 = new List<FileInfo>();
string strPath = @"D:\program";
List<FileInfo> lstFiles = getFile(strPath, ".docx", lst);
List<FileInfo> lstFiles1 = getFile(strPath, ".exe", lst1);
foreach (FileInfo shpFile in lstFiles)
{
listBox1.Items.Add(shpFile.FullName + "\n");
}
foreach (FileInfo shpFile1 in lstFiles1)
{
listBox2.Items.Add(shpFile1.FullName + "\n");
}
}
public static List<FileInfo> getFile(string path, string extName, List<FileInfo> lst)
{
try
{
string[] dir = Directory.GetDirectories(path); //文件夹列表
DirectoryInfo fdir = new DirectoryInfo(path);
FileInfo[] file = fdir.GetFiles();
//FileInfo[] file = Directory.GetFiles(path); //文件列表
if (file.Length != 0 || dir.Length != 0) //当前目录文件或文件夹不为空
{
foreach (FileInfo f in file) //显示当前目录所有文件
{
if (extName.ToLower().IndexOf(f.Extension.ToLower()) >= 0)
{
lst.Add(f);
}
}
foreach (string d in dir)
{
getFile(d, extName, lst);//递归
}
}
return lst;
}
catch (Exception ex)
{
throw ex;
}
}
}
}
运行结果: