0

How could I change this to determine the text files in its directory itself?

string[] file = new string[] {
    "abc",
    "def",
    "file3"};
var files = (UInt16)file.Length;
for (UInt16 n = 0; n < files; n++)
{
    var streamReader =
        new System.IO.StreamReader(
            file[n] + ".txt");
    ...
    streamReader.Close();
    ...
}
2
  • 2
    If the answers below are not answering your question, then consider making your question clear. I have no idea what you are trying to do. Jun 18, 2012 at 12:40
  • Ribtoks, Tigran and Eren Ersönmez all provided correct answers quickly, having had no problem with the question. Whats more all of the answers to this question are correct and relevant. I'd recomend you message them and ask for advice with the subject and comprehension.
    – alan2here
    Jun 18, 2012 at 12:45

4 Answers 4

6
string[] files = Directory.GetFiles(@"c:\MyDir\", "*.txt");

Update Some usage:

foreach (var filename in files)
{
    string allText = File.ReadAllText(filename);
    // or string[] lines = File.ReadLines(filename);
}
3

Can use Directory.GetFiles, like this more or less

string[] dirs = Directory.GetFiles(@"/*Parent directory*/", "*.txt");

If this is not what you're asking for , please clarify.

3

Use Directory.GetFiles

var files = Directory.GetFiles(Directory.GetCurrentDirectory(),"*.txt");

And if you want to include subdirectories:

var files = Directory.GetFiles(Directory.GetCurrentDirectory(),"*.txt",
    SearchOption.AllDirectories);
1

Try to post the Clear Question so that you will get the Correct answer .

If you want to get the all files of type "*.txt". Try this code

DirectoryInfo dir = new DirectoryInfo("Path");
var allTextFiles = dir.GetFiles("*.txt", SearchOption.AllDirectories);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.