Skip to main content
 首页 » 编程设计

c#之从短文件名获取完整路径

2024年02月13日14kevingrace

我可以从文件名中获取完整路径吗,例如从 test.txt 中获取完整目录路径,或者有什么方法可以保存它

我问这个问题的原因是我正在制作一个像 Notepad++ 这样的应用程序,你们中的一些人可能听说过它。更改选项卡控件选项卡时,我希望表单的文本是完整目录,而选项卡文本只是 filename.format

我目前的代码

private void tabControl1_TabIndexChanged(object sender, EventArgs e) 
{ 
    if (tabControl1.SelectedTab.Text.StartsWith("New")) 
    { 
       int count = tabControl1.TabCount - 1; 
       this.Text = tabControl1.Controls[count].Text + " - My Note 1.0"; 
    } 
    //It is a directory and i need to make the forms text the path here? 
} 

请您参考如下方法:

您可以使用 System.IO.Path.GetFullPath :

var fullPath = Path.GetFullPath("test.txt"); 

If you pass in a short file name, it is expanded to a long file name.

If c:\temp\newdir is the current directory, calling GetFullPath on a file name such as test.txt returns c:\temp\newdir\test.txt.

如果您想从中获取路径,请使用 System.IO.Path.GetDirectoryName

var path = Path.GetDirectoryName(fullPath)