文件操作小结

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) { 
 
        }
    }


你可能感兴趣的:(文件操作小结)