简体   繁体   English

无法获取文件的绝对路径

[英]Trouble getting absolute path of a file

I have a script editor which includes tabs. 我有一个包含选项卡的脚本编辑器。 Each tab page has a header which includes the file's name. 每个选项卡页都有一个包含文件名的标题。 I also have the following code: 我也有以下代码:

string fileName = tabControl.SelectedTab.Text;
string filePath = Path.GetFullPath(fileName);

The above code should return the absolute path of fileName . 上面的代码应返回fileName的绝对路径。 However, I've figured out that it actually returns the absolute path of my script editor's .exe! 但是,我发现它实际上返回了脚本编辑器.exe的绝对路径!

Why does that happen? 为什么会这样呢? I've tested it and yes, fileName does have the corrent file name, so why doesn't Path.GetFullPath() work? 我已经对其进行了测试,是的, fileName确实具有相应的文件名,那么Path.GetFullPath()为什么不起作用?

You must keep information about absolute path of the file - there is no way to construct it back based on just file name. 您必须保留有关文件绝对路径的信息-无法仅基于文件名来构造它。

Why Path.GetFullPath(fileName) does not work: this method converts relative path to file into absolute based on current working directory . 为什么Path.GetFullPath(fileName)不起作用:此方法根据当前工作目录将文件的相对路径转换为绝对路径。 That location can change while program is running (ie when using file open dialog) and by default starts in your exe file directory (which usually have nothing to do with location of your text files). 该位置可以在程序运行时(即,使用文件打开对话框时)更改,并且默认情况下在exe文件目录中启动(通常与文本文件的位置无关)。

It should work if you create a FileInfo object and use the FullName property. 如果创建FileInfo对象并使用FullName属性,它应该可以工作。

The answer to the wonky behaviour of Path.GetFullPath probably lies on MSDN , but this snip alone raises red flags for me: Path.GetFullPath行为的Path.GetFullPath可能在MSDN上 ,但是仅此Path.GetFullPath对我来说是一个Path.GetFullPath

The file or directory specified by path is not required to exist. 路径指定的文件或目录不需要存在。 For example, if c:\\temp\\newdir is the current directory, calling GetFullPath on a file name such as test.txt returns c:\\temp\\newdir\\test.txt. 例如,如果c:\\ temp \\ newdir是当前目录,则对文件名(例如test.txt)调用GetFullPath将返回c:\\ temp \\ newdir \\ test.txt。 The file need not exist. 该文件不需要存在。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM