-3

string [] filenames = openFileDialog1.FileNames;

How can I read this array?

Would I need to set each file path to its own string??? I'm clueless.

wizlog
  • 302
  • 7
  • 22
  • 1
    it is not clear what you mean, please provide more information – thumbmunkeys Aug 21 '11 at 22:25
  • 2
    Can you please clarify... what exactly are you trying to do? – Jason Down Aug 21 '11 at 22:25
  • 2
    So, http://msdn.microsoft.com/en-us/library/system.windows.forms.filedialog.filenames.aspx gives info on the `FileNames` property. Are you trying to open them and read them or just iterate through them? They are *already* strings in an array so you can just `foreach` through them if you like. You'll need to provide more info so that we know what you are trying to do. – itsmatt Aug 21 '11 at 22:27

2 Answers2

0

Do you mean access the elements in the array?

for (int i = 0; i < filenames.Length; i++)
    MyDoSomethingMethod(filenames[i]);

As pointed out by another answer you can also use a foreach to access each item

foreach (String filename in filenames)
    DoSomething(filename);

When you access filenames[some_index] you access the string already so there's no need to save it to another variable to work with it same applies to foreach loop.

Jesus Ramos
  • 22,940
  • 10
  • 58
  • 88
0

Assuming you want to loop thru the filenames and do something with each file, here's a sample:

foreach (String file in openFileDialog1.FileNames) 
{
    // read file lines
    try
    {

        using (StreamReader sr = File.OpenText(file))
        {
            String input;
            while ((input = sr.ReadLine()) != null)
            {
                Console.WriteLine(input);
            }
            Console.WriteLine ("The end of the stream has been reached.");
        }


    }
    catch (SecurityException ex)
    {
        // The user lacks appropriate permissions to read files, discover paths, etc.
        Console.WriteLine ("Security error. Please contact your administrator for details.\n\n" +
            "Error message: " + ex.Message + "\n\n" +
            "Details (send to Support):\n\n" + ex.StackTrace
        );
    }
    catch (Exception ex)
    {
        // Could not load the file - probably related to Windows file system permissions.
        Console.WriteLine ("Cannot display the file: " + file.Substring(file.LastIndexOf('\\'))
            + ". You may not have permission to read the file, or " +
            "it may be corrupt.\n\nReported error: " + ex.Message);
    }
}
Mrchief
  • 75,126
  • 20
  • 142
  • 189