2015-11-08 94 views
1
private void addGifsToolStripMenuItem_Click(object sender, EventArgs e) 
     { 
      OpenFileDialog theDialog = new OpenFileDialog(); 
      theDialog.Title = "Add Gif Files"; 
      theDialog.Filter = "GIF files|*.gif"; 
      theDialog.InitialDirectory = @"C:\"; 
      theDialog.Multiselect = true; 
      if (theDialog.ShowDialog() == DialogResult.OK) 
      { 
       try 
       { 
        string[] files = theDialog.SafeFileNames; 
        allfiles = new List<string>(files); 
        label2.Text = allfiles.Count.ToString(); 
        if (allfiles.Count > 1) 
        { 
         button2.Enabled = true; 
        } 
       } 
       catch (Exception ex) 
       { 
        MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message); 
       } 
      } 
      else 
      { 
       allfiles = new List<string>(); 
       label2.Text = "0"; 
      } 
     } 

都来自同一个目录,我需要以某种方式,每次得到的文件目录名称添加的文件我点击确定如何从OpenFileDialog中提取文件的路径名?

行后:label2.Text =“0”;获取文件目录路径。

+0

你是什么意思?点击确定后,进入'if'部分而不是'else'部分 –

+0

我的意思是在对话框中我要去一个目录选择文件,然后单击确定我想要获取文件所在的目录中的字符串变量。例如:我从c:\中选择了4个文件,所以现在在所有文件中,我将看到1.gif,2.gif,3.gif ....现在我想在另一个变量中选择路径来查看c:\,例如,我去了e:\ myimages,并选择了一些文件,我将在allfiles中看到:1.gif,2.gif,3.gif现在在selectedpath中的螺母,我将看到e:\ myimages –

回答

1

您可以使用Path.GetDirectoryName(filePath);来获取目录的名称对于任何给定文件路径:

string directoryName = Path.GetDirectoryName(theDialog.FileName); 

或:

foreach(string file in theDialog.FileNames) 
{ 
    directoryNameList.Add(Path.GetDirectoryName(file)); 
}