如何从文件名获取完整的文件路径?

17

如何获取给定文件的完整路径?

例如,我提供:

string filename = @"test.txt";

结果应该是:

Full File Path = C:\Windows\ABC\Test\test.txt

你想在你的驱动器上搜索 test.txt 文件并返回其路径,还是你想将一些默认路径附加到该文件? - Habib
由于标志时间和更改之间,这里是具有完全重复的更新链接 https://dev59.com/O3RB5IYBdhLWcg3wH0SW - Prix
9个回答

17

尝试

string fileName = "test.txt";
FileInfo f = new FileInfo(fileName);
string fullname = f.FullName;

嗨,感谢回复。 它返回当前目录, 但我需要从所有目录中获取。 - Ranjeeth Kumar Pathi

11

8

您可以使用以下方法:

string path = Path.GetFullPath(FileName);

它将返回所提到文件的完整路径。

7

Directory.GetCurrentDirectory

string dirpath = Directory.GetCurrentDirectory();

在文件名前添加此目录路径以获取完整路径。

正如@Dan Puzey在评论中指出的那样,最好使用Path.Combine

Path.Combine(Directory.GetCurrentDirectory(), filename)

2
请使用 Path.Combine,而不是在前面添加。 - Dan Puzey

5
我知道我的回答可能太晚了,但它可能对其他人有帮助
尝试一下。
Void Main()
{
string filename = @"test.txt";
string filePath= AppDomain.CurrentDomain.BaseDirectory + filename ;
Console.WriteLine(filePath);
}

根据Microsoft Docs的说明,BaseDirectory被用于“程序集解析器探测程序集”。它解析为可执行文件路径(而不是工作目录),例如“bin/Debug/...”。因此,在某些边缘情况下,它只能解决OP的问题,其中工作目录和可执行目录相同。在大多数其他情况下,当前用户将无法访问可执行目录。 - Zane Claes

3

尝试..

Server.MapPath(FileUpload1.FileName);

如果我理解问题正确的话,MapPath确实是正确的方法。你可以在这个链接上找到更多关于MapPath的信息:http://msdn.microsoft.com/en-us/library/system.web.httpserverutility.mappath.aspx - JP Hellemons
HttpContext 在 WinForms 中不可用。 - Abdul Munim
1
Server.MapPath 适用于 IIS/web 应用程序。该问题的标签是 windows。 - Habib
我需要用于Windows窗体的。 - Ranjeeth Kumar Pathi

2

尝试:

string fileName = @"test.txt";
    string currentDirectory = Directory.GetCurrentDirectory();
    string[] fullFilePath = Directory.GetFiles(currentDirectory, filename, SearchOption.AllDirectories);

它将返回当前目录及其子目录中所有这些文件的完整路径到字符串数组fullFilePath。如果只有一个文件存在,则该文件将在“fullFileName [0]”中。


1
private const string BulkSetPriceFile = "test.txt";
...
var fullname = Path.GetFullPath(BulkSetPriceFile);

0

您可以获取当前路径:

string AssemblyPath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location).ToString();

祝你好运!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接