string[]文件名=openFileDialog1.filenames;
如何读取此数组?
是否需要将每个文件路径设置为其自己的字符串???我一无所知。
您的意思是访问数组中的元素吗?
for (int i = 0; i < filenames.Length; i++)
MyDoSomethingMethod(filenames[i]);
正如另一个答案所指出的,你也可以使用foreach来访问每个项目
foreach (String filename in filenames)
DoSomething(filename);
当您访问文件名[some_index]时,您已经访问了字符串,因此无需将其保存到另一个变量中即可使用它。foreach循环也是如此。
假设您想遍历文件名并对每个文件执行某些操作,下面是一个示例:
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.nn" +
"Error message: " + ex.Message + "nn" +
"Details (send to Support):nn" + 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.nnReported error: " + ex.Message);
}
}