文件对话框获取完整路径

时间:2019-07-03 12:41:50

标签: c#

我有一个OpenFileDialog,我只需要一个完整路径即可,例如“ C:\ Users \ Tshililo \ example.csv”。选择文件后如何获取路径?

我尝试使用System.IO.Path.GetFileName(ofd.File.Name);,但输出为“ example.csv”。

    OpenFileDialog ofd = new OpenFileDialog();
    using (var stream = ofd.File.OpenRead())
            {
      var thiname = System.IO.Path.GetFileName(ofd.File.Name);
                    //var oldPath = 
      System.IO.Path.GetDirectoryName(ofd.File.Name);

                }

我的预期结果是“ C:\ Users \ Tshililo \ example.csv”

2 个答案:

答案 0 :(得分:1)

FileDialog.FileName docs

  

文件名包括文件路径和扩展名。如果未选择任何文件,则此方法返回一个空字符串(“”)。

<key>CFBundleDisplayName</key> <string>$(PRODUCT_NAME)</string> 继承自ab_final = join_df.withColumn("linked_A_B", when( col("a3_inbound").isNull() & ("a3_item").isNull() ), 'No Value' ).when( (col("it_item").isNull() & ("it_export").isNull()), 'NoShipment' ).when( (col("a3_inbound").isNotNull() & ("it_export").isNotNull()), 'Export') ) 类。

答案 1 :(得分:1)

这就是我使用OpenFileDialog的方式。

  • 调用ShowDialog()将显示对话框,并在用户选择文件时暂停程序执行。他们说“确定​​”或“取消”后,它会恢复。
  • 检查ShowDialog()的结果-如果可以,那么我们可以继续处理用户选择的文件。最关键的是,.FileName属性包含文件的完整路径。
  • 如果启用了Multiselect,则可以在.FileNames属性中找到多个文件名。 .FileName包含与.FileNames[0]相同的字符串,.FileNames中名称的顺序通常与用户选择它们的顺序相反。如果您的用户期望某种有序的处理,请自己手动对文件名进行排序。在返回的文件名的顺序上加上任何特殊含义
  • 是不明智的

//consider declaring this in a USING if you don't have one persistent 
//openfiledialog that you re-use in your app
//i typically keep just one OFD at class level and hide/show it repeatedly
var ofd = new OpenFileDialog();

//set options of ofd before show
ofd.Whatever = whatever;

if(ofd.ShowDialog() == DialogResult.OK){

  //some examples:
  //we could get the full file path the user chose
  var path = ofd.FileName; 

  //or we could delete the file
  File.Delete(ofd.FileName); //2) delete the file or..

  //or we could read the contents of the text file they picked
  var content = File.ReadAllText(ofd.FileName); 

  //or open it as a stream
  var stream = File.OpenStream(ofd.FileName); 

  //or we could get the directory the file is in
  var dir = Path.GetDirectory(ofd.FileName);

  //or we could ponder how deep the directory tree is
  var depth = ofd.FileName.Split(Path.DirectorySeparatorChar.ToString()).Length;

}