0

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.

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 (e.g. "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. 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.

  • 2
    Is the order number within the filename or the file's content? – Hanlet Escaño Apr 05 '13 at 20:25
  • Do you want to search inside the file, or the file name contains the order No. e.g. some_file_name_123.txt , Is 123 the order no. I recommend you to use order no. as a part of file name – Muhammad Amin Apr 05 '13 at 20:27
  • 1
    Check out [this question](http://stackoverflow.com/questions/929276/how-to-recursively-list-all-the-files-in-a-directory-in-c) on how to do a recursive directory search. That lists all files in a directory and its subfolders, but it gives you an idea for what to do. Next take a look at [streamreader](http://msdn.microsoft.com/en-us/library/system.io.streamreader.aspx) to read in the actual file. Usually people on SO won't code it for you, so this is a good place to start. – tnw Apr 05 '13 at 20:28
  • The simple way would be to generate a list of files that will be read. Read each file until you determine which file contained the order number in question. Place the contents of the entire into the RichTextBox. All three parts of this process is well documented more effort on your part is required to really help you. – Security Hound Apr 05 '13 at 20:42

1 Answers1

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

Sten Petrov
  • 10,943
  • 1
  • 41
  • 61