简体   繁体   English

c#在文本文件中搜索特定字符串并获取文件路径

[英]c# Search text files for specific string and get file path

Using c# in a Windows Form I need to search a directory "C:\\XML\\Outbound" for the file that contains an order number 3860457 and return the path to the file that contains the order number so I can then open the file and display the contents to the user in a RickTextBox. 我需要在Windows窗体中使用c#,我需要在目录"C:\\XML\\Outbound"搜索包含订单号3860457的文件,并将路径返回到包含订单号的文件,这样我就可以打开文件并显示在RickTextBox中向用户显示内容。

The end user will have the order number but will not know what file contains that order number so that is why I need to search all files till it finds the filecontaining the order number and return the path (eg "C:\\XML\\Outbound\\some_file_name_123.txt" ) 最终用户将拥有订单号,但不知道哪个文件包含该订单号,因此这就是为什么我需要搜索所有文件,直到找到包含订单号的文件并返回路径(例如"C:\\XML\\Outbound\\some_file_name_123.txt"

I am somewhat new to c# so I am not even sure where to start with this. 我对C#有点陌生,所以我什至不知道从哪里开始。 Any direction for this? 有什么方向吗?

Sorry the order number is inside the file so I need to search each file contents for the order number and once the file containing the order number is found return the path to that file. 抱歉,订单号在文件内,所以我需要在每个文件内容中搜索订单号,找到包含订单号的文件后,请返回该文件的路径。 Order number is not part of the file name. 订单号不是文件名的一部分。

Straight answer: 直接回答:

public string GetFileName(string search){ 
    List<string> paths = Directory.GetFiles(@"C:\XML\Outbond","*.txt",SearchOption.AllDirectories).ToList();
    string path = paths.FirstOrDefault(p=>File.ReadAllLines(p).Any(line=>line.IndexOf(search)>=0));
    return path;    
}

Not-so straight answer: 不那么直接的答案:

Even though the above function will give you the path for given string (some handling of errors and edge cases may be nice) it will be terribly slow, especially if you have lots of files. 即使上面的函数为您提供了给定字符串的路径(对错误和边缘情况的某些处理可能会很好),但它的运行速度却非常慢,尤其是在文件很多的情况下。 If that's the case you need to tell us more about your environment because chances are you're doing it wrong (: 如果是这种情况,您需要告诉我们更多有关您的环境的信息,因为您可能做错了(:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM