如何从文件的完整路径获取目录?
获取文件所在目录的最简单方法是什么? 我用它来设置工作目录。
string filename = @"C:\MyDirectory\MyFile.bat";
在这个例子中,我应该得到“C:\MyDirectory”。
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".
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(10)
如果您确实有绝对路径,请使用
Path .GetDirectoryName(路径)
。如果您可能只有相对名称,请使用
new FileInfo(path).Directory.FullName
。请注意,
Path
和FileInfo
均位于命名空间System.IO
中。If you definitely have an absolute path, use
Path.GetDirectoryName(path)
.If you might only have a relative name, use
new FileInfo(path).Directory.FullName
.Note that
Path
andFileInfo
are both found in the namespaceSystem.IO
.您可以使用
System.IO.Path.GetDirectoryName(fileName)
,或使用FileInfo.Directory
将路径转换为FileInfo
。如果您使用路径执行其他操作,
FileInfo
类可能具有优势。You can use
System.IO.Path.GetDirectoryName(fileName)
, or turn the path into aFileInfo
usingFileInfo.Directory
.If you're doing other things with the path, the
FileInfo
class may have advantages.您可以使用 Path.GetDirectoryName 并仅传入文件名。
MSDN 链接
You can use
Path.GetDirectoryName
and just pass in the filename.MSDN Link
如果您正在使用
FileInfo
对象,则有一种简单的方法可以通过DirectoryName
属性提取目录完整路径的string
表示形式。通过 MSDN 对
FileInfo.DirectoryName
属性的描述:示例用法:
链接到 MSDN 文档。
If you are working with a
FileInfo
object, then there is an easy way to extract astring
representation of the directory's full path via theDirectoryName
property.Description of the
FileInfo.DirectoryName
Property via MSDN:Sample usage:
Link to the MSDN documentation.
您可以使用以下方法获取当前的应用程序路径:
You can get the current Application Path using:
首先,您必须使用 System.IO 命名空间。 然后;
或者
First, you have to use System.IO namespace. Then;
or
大多数情况下,您可以使用 Path.GetFullPath 。
但是,如果您还想在文件名相对定位的情况下获取路径,则可以使用以下通用方法:
例如:
GetPath("C:\Temp\Filename.txt")
return"C:\Temp\"
GetPath("Filename.txt")
返回当前工作目录
就像"C:\温度\"
You can use
Path.GetFullPath
for most of the case.But if you want to get the path also in the case of the file name is relatively located then you can use the below generic method:
For example:
GetPath("C:\Temp\Filename.txt")
return"C:\Temp\"
GetPath("Filename.txt")
returncurrent working directory
like"C:\Temp\"
就我而言,我需要找到(目录的)完整路径的目录名称,所以我简单地执行了以下操作:
In my case, I needed to find the directory name of a full path (of a directory) so I simply did: