0

在 Windows 窗体中使用 c# 我需要在目录"C:\XML\Outbound"中搜索包含订单号的文件3860457并返回包含订单号的文件的路径,以便我可以打开文件并在 RickTextBox 中向用户显示内容。

最终用户将拥有订单号,但不知道哪个文件包含该订单号,这就是为什么我需要搜索所有文件直到找到包含订单号的文件并返回路径(例如"C:\XML\Outbound\some_file_name_123.txt"

我对 c# 有点陌生,所以我什至不确定从哪里开始。这有什么方向吗?

抱歉,订单号在文件中,所以我需要在每个文件内容中搜索订单号,一旦找到包含订单号的文件,就返回该文件的路径。订单号不是文件名的一部分。

4

1 回答 1

4

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 (:

于 2013-04-05T20:31:15.070 回答