如何用c语言输出文件路径,关于c:如何从文件的完整路径获取目录?

这篇博客探讨了在C#中获取文件所在目录的各种方法,包括使用Path.GetDirectoryName()和FileInfo.Directory.FullName等。文章提供了示例代码,并强调了使用专用方法避免字符串操作的风险。此外,还讨论了如何处理相对和绝对路径的情况。
摘要由CSDN通过智能技术生成

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

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\"。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值