如何从文件的完整路径获取目录? [英] How do I get the directory from a file's full path?

查看:145
本文介绍了如何从文件的完整路径获取目录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

获取文件目录的最简单方法是什么?我正在使用它设置一个工作目录。

  string filename = @C:\MyDirectory\MyFile.bat ; 

在这个例子中,我应该得到C:\MyDirectory。

解决方案

如果您绝对有绝对路径,请使用 Path.GetDirectoryName(path)



如果您只能获得相对名称,请使用新的FileInfo(路径).Directory.FullName



请注意, Path FileInfo 都位于命名空间 System.IO中


What is the simplest way to get the directory that a file is in? I'm using this to set a working directory.

string filename = @"C:\MyDirectory\MyFile.bat";

In this example, I should get "C:\MyDirectory".

解决方案

If you've definitely got an absolute path, use Path.GetDirectoryName(path).

If you might only get a relative name, use new FileInfo(path).Directory.FullName.

Note that Path and FileInfo are both found in the namespace System.IO.

这篇关于如何从文件的完整路径获取目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆