특정 파일 유형에서 문자열을 검색하는 간단한 프로그램을 수행했지만 찾지 못했습니다.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Security.AccessControl;
using System.Security.Principal;
using System.Runtime.InteropServices;
namespace Search_Text_In_Files
{
public partial class Form1 : Form
{
StreamWriter w = new StreamWriter(@"e:\textresults.txt");
public Form1()
{
InitializeComponent();
backgroundWorker1.RunWorkerAsync();
}
bool result = false;
public List<string> FindLines(string DirName, string TextToSearch)
{
int counter = 0;
List<string> findLines = new List<string>();
DirectoryInfo di = new DirectoryInfo(DirName);
List<FileInfo> l = new List<FileInfo>();
CountFiles(di, l);
int totalFiles = l.Count;
int countFiles = 0;
if (di != null && di.Exists)
{
if (CheckFileForAccess(DirName) == true)
{
foreach (FileInfo fi in l)
{
backgroundWorker1.ReportProgress((int)((double)countFiles / totalFiles * 100.0), fi.Name);
countFiles++;
System.Threading.Thread.Sleep(1);
if (string.Compare(fi.Extension, ".cs", true) == 0)
{
using (StreamReader sr = fi.OpenText())
{
string s = "";
while ((s = sr.ReadLine()) != null)
{
if (s.Contains(TextToSearch))
{
counter++;
findLines.Add(s);
result = true;
backgroundWorker1.ReportProgress(0, fi.FullName);
}
}
}
}
}
}
}
return findLines;
}
private void CountFiles(DirectoryInfo di, List<FileInfo> l)
{
try
{
l.AddRange(di.EnumerateFiles());
}
catch
{
}
try
{
IEnumerable<DirectoryInfo> subDirs = di.EnumerateDirectories();
if (subDirs.Count() > 0)
{
foreach (DirectoryInfo dir in subDirs)
CountFiles(dir, l);
}
}
catch
{
string err = "";
}
}
private bool CheckForAccess(string PathName)
{
if (File.Exists(PathName) == true)
return CheckFileForAccess(PathName);
if (Directory.Exists(PathName) == true)
return CheckFolderForAccess(PathName);
return false;
}
private bool CheckFileForAccess(string FileName)
{
FileSecurity fs = new FileSecurity(FileName, AccessControlSections.Access);
if (fs == null)
return false;
AuthorizationRuleCollection TheseRules = fs.GetAccessRules(true, true, typeof(NTAccount));
if (TheseRules == null)
return false;
return CheckACL(TheseRules);
}
private bool CheckFolderForAccess(string FolderName)
{
DirectoryInfo di = new DirectoryInfo(FolderName);
if (di == null)
return false;
DirectorySecurity acl = di.GetAccessControl(AccessControlSections.Access);
if (acl == null)
return false;
AuthorizationRuleCollection TheseRules = acl.GetAccessRules(true, true, typeof(NTAccount));
if (TheseRules == null)
return false;
return CheckACL(TheseRules);
}
private bool CheckACL(AuthorizationRuleCollection TheseRules)
{
foreach (FileSystemAccessRule ThisRule in TheseRules)
{
if ((ThisRule.FileSystemRights & FileSystemRights.Read) == FileSystemRights.Read)
{
if (ThisRule.AccessControlType == AccessControlType.Deny)
return false;
}
}
return true;
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
FindLines(@"d:\c-sharp", "FileShellExtension");
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
label2.Text = e.UserState.ToString();
if (result == true)
{
listView1.Items.Add(e.UserState.ToString());
result = false;
}
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled == true)
{
}
else if (e.Error != null)
{
}
else
{
}
}
}
}
이 경우 d : \ c-sharp 디렉터리에서 "FileShellExtension"문자열을 찾고 있으며 예를 들어 form1.cs와 같이 cs로 끝나는 파일에서만
그리고 내가 얻는 유일한 결과는이 프로그램에서 "FileShellExtension"문자열이 여기에 존재하기 때문에 결과로 줄을 찾는 것입니다.
FindLines(@"d:\c-sharp", "FileShellExtension");
다른 프로젝트에서는 다음과 같은 form1에 "FileShellExtension"문자열이 있습니다.
NameSpace FileShellExtension
그러나 그것을 찾지 못했습니다.
이 프로그램에서 발견되는 문자열의 결과를 전달하기 위해 먼저 수행하려는 것은 검색 프로그램이 결과가 아니어야합니다.
둘째, NameSpace FileShellExtension의 일부로 문자열을 찾지 못한 이유는 무엇입니까?
현재 FindLines
서명을 다음으로 변경하는 것이 좋습니다.
public static IEnumerable<String> FindLines(String dirName, String textToSearch) {
if (null == dirName)
throw new ArgumentNullException("dirName");
else if (null == textToSearch)
throw new ArgumentNullException("textToSearch");
//TODO: put a right mask instead of *.txt
var files = Directory
.EnumerateFiles(dirName, "*.txt", SearchOption.AllDirectories)
.Where(file => true); //TODO: put right condition on file (now all accepted)
return files
.SelectMany(file => File.ReadLines(file))
.Where(line => line.Contains(textToSearch));
}
그런 다음 (루틴을 디버깅 한 경우) 백그라운드 작업자 또는 기타를 추가하는 동안 결과를 구체화 할 수 있습니다.
public static List<String> FindLinesToList(String dirName, String textToSearch) {
List<String> result = new List<String>();
foreach (var item in FindLines(dirName, textToSearch)) {
backgroundWorker1.ReportProgress(...)
countFiles++;
...
result.Add(item);
}
}
디버깅이 훨씬 쉽습니다. 예를 들어
var files = Directory
...
으로
var files = new String[@"C:\MyFile.txt"];
파일의 검색이 올바른지 테스트하십시오.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다