1,遍歷
C#遍歷指定文件夾中的所有文件
DirectoryInfo TheFolder=new DirectoryInfo(folderFullName);
//遍歷文件夾
foreach(DirectoryInfo NextFolder in TheFolder.GetDirectories())
this.listBox1.Items.Add(NextFolder.Name);
//遍歷文件
foreach(FileInfo NextFile in TheFolder.GetFiles()) //foreach(FileInfo NextFile in TheFolder.GetFiles(“*.cs”)) 找類文件
this.listBox2.Items.Add(NextFile.Name);
FileInfo.Exists:獲取指定文件是否存在;
FileInfo.Name,FileInfo.Extensioin:獲取文件的名稱和擴展名;
FileInfo.FullName:獲取文件的全限定名稱(完整路徑);
FileInfo.Directory:獲取文件所在目錄,返回類型為DirectoryInfo;
FileInfo.DirectoryName:獲取文件所在目錄的路徑(完整路徑);
FileInfo.Length:獲取文件的大小(字節數);
FileInfo.IsReadOnly:獲取文件是否只讀;
FileInfo.Attributes:獲取或設置指定文件的屬性,返回類型為FileAttributes枚舉,可以是多個值的組合
FileInfo.CreationTime、FileInfo.LastAccessTime、FileInfo.LastWriteTime:分別用於獲取文件的創建時間、訪問時間、修改時間;
2,讀寫
//創建並寫入(將覆蓋已有文件)
if (!File.Exists(path))
{
using (StreamWriter sw = File.CreateText(path))
{
sw.WriteLine("Hello");
}
}
//讀取文件
using (StreamReader sr = File.OpenText(path))
{
string s = "";
while ((s = sr.ReadLine()) != null)
{
Console.WriteLine(s);
if (s.IndexOf("aaa") != -1)
{
//.... 搜索文件是否包含某關鍵字
}
}
}
//刪除/拷貝
try
{
File.Delete(path);
File.Copy(path, @"f:\tt.txt");
}
catch (Exception e)
{
Console.WriteLine("The process failed: {0}", e.ToString());
}
}
//查找關鍵字是否存在於指定目標所有文件中的任一
private void SearchKeyWordListInDirectroyFiles(string DirectoryPath, IList KeyWordsList,string filePattern ) {
//KeyWordsList,關鍵字集合,filePattern指定搜索哪些文件,notFile指定不搜索哪個文件
try
{
DirectoryInfo di = new DirectoryInfo(DirectoryPath);
foreach (FileInfo NextFile in di.GetFiles(filePattern))
{
using (StreamReader sr = NextFile.OpenText())
{
string s = "";
while ((s = sr.ReadLine()) != null)
{
for (int i = 0; i < KeyWordsList.Count; i++)
{
if (s.IndexOf(KeyWordsList[i].ToString()) != -1)
{
KeyWordsList.RemoveAt(i);
}
}
}
}
}
foreach (DirectoryInfo NextFolder in di.GetDirectories())
{
SearchKeyWordListInDirectroyFiles(NextFolder.FullName, KeyWordsList, filePattern);
}
}
catch (Exception e) {
}
}