获取文件所在目录的最简单方法是什么?我用这个来设置一个工作目录。
string filename = @"C:\MyDirectory\MyFile.bat";
在这个例子中,我应该得到"c:mydirectory"。
那不应该是字符串吗?@"C:\MyDirectory\MyFile.bat"
有人想保护这个问题吗?谁有权这样做?11个与2017年最后一个类似的答案。
如果您确定有绝对路径,请使用Path.GetDirectoryName(path)。
如果您可能只得到一个相对名称,请使用new FileInfo(path).Directory.FullName。
注意,Path和FileInfo都在名称空间System.IO中找到。
确实如此,但是否有一个名为getdirectory的方法?不是GetDirectoryName吗?
您可以只使用directoryname而不是directory.fullpath,可以吗?
我不想收到亲戚的名字。我没有发现这条路是绝对的。我现在有两个版本:)
敏捷回答……回答、重构、重构、重构;-)
你用snippy检查那个吗?;)
System.IO.Path.GetDirectoryName(filename)
更新以提及命名空间。
Path.GetDirectoryName(filename);
您可以使用System.IO.Path.GetDirectory(filename),或者将路径转换为FileInfo,然后使用FileInfo.Directory。
如果你在这条道路上做其他事情,那么FileInfo可能有优势。
path类中没有"getdirectory方法;您的意思必须是"getdirectoryname"
您可以使用Path.GetDirectoryName,只需输入文件名即可。
MSDN链路
使用下面提到的代码获取文件夹路径
Path.GetDirectoryName(filename);
在您的情况下,这将返回"c:mydirectory"
您可以使用以下方法获取当前应用程序路径:
string AssemblyPath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location).ToString();
祝你好运!
如果您使用的是FileInfo对象,那么有一种简单的方法可以通过DirectoryName属性提取目录完整路径的string表示。
通过msdn对FileInfo.DirectoryName属性的描述:
Gets a string representing the directory's full path.
样品使用情况:
string filename = @"C:\MyDirectory\MyFile.bat";
FileInfo fileInfo = new FileInfo(filename);
string directoryFullPath = fileInfo.DirectoryName; // contains"C:\MyDirectory"
链接到msdn文档。
在我的例子中,我需要找到一个完整路径(目录)的目录名,所以我只需要:
var dirName = path.Split('\').Last();
OP需要"C:\MyDirectory",而不是MyDirectory。使用字符串操作方法的建议是有风险的,有许多陷阱,而使用专用的Path方法。
首先,必须使用System.IO命名空间。然后;
string filename = @"C:\MyDirectory\MyFile.bat";
string newPath = Path.GetFullPath(fileName);
或
string newPath = Path.GetFullPath(openFileDialog1.FileName));
只是在别人需要它的时候,我用在我的相对路径上的是:
string rootPath ="MyRootDir/MyFolder1/MyFolder2/myFile.pdf";
while (!string.IsNullOrWhiteSpace(Path.GetDirectoryName(rootPath)))
{
rootPath = Path.GetDirectoryName(rootPath);
}
Console.WriteLine(rootPath); //Will print:"MyRootDir"
在大多数情况下,您可以使用Path.GetFullPath。但是,如果您还想获取路径(如果文件名相对位置),则可以使用以下通用方法:
string GetPath(string filePath)
{
return Path.GetDirectoryName(Path.GetFullPath(filePath))
}
例如:
GetPath("C:\Temp\Filename.txt")返回"C:\Temp\"。
GetPath("Filename.txt")返回current working directory类"C:\Temp\"。