如何在C#中解析相对路径

9

我有一个路径合并的函数。例如:

我的应用程序位于 D:\toto\titi\tata\myapplication.exe

我创建了一个基于我的应用程序路径(D:\toto\titi\tata\myapplication.exe)解决相对路径的Windows窗体应用程序(C#)。

我想要做到这些:

1)需要解决的路径为test.txt => D:\toto\titi\tata\test.txt

2)需要解决的路径为.\..\..\test\test.txt => D:\toto\test\test.txt

3)需要解决的路径为.\..\test\test.txt => D:\toto\titi\test\test.txt

4)需要解决的路径为.\..\..\..\test\test.txt => D:\test\test.txt

5)需要解决的路径为.\..\..\..\..\test\test.txt => 路径不存在

6)需要解决的路径为\\server\share\folder\test => 获取服务器上对应的路径

我使用了这个方法

private void btnSearchFile_Click(object sender, EventArgs e)
{
    // Open an existing file, or create a new one.
    FileInfo fi = new FileInfo(@"D:\toto\titi\tata\myapplication.exe");

    // Determine the full path of the file just created or opening.
    string fpath = fi.DirectoryName;

    // First case.
    string relPath1 = txtBoxSearchFile.Text;
    FileInfo fiCase1 = new FileInfo(Path.Combine(fi.DirectoryName, relPath1.TrimStart('\\')));

    //Full path
    string fullpathCase1 = fiCase1.FullName;

    txtBoxFoundFile.Text = fullpathCase1;
}

但我没有解决1)点、5)点和6)点。你能帮我吗?

1
Environment.CurrentDirectory和Server.MapPath :) - Icepickle
3
你不能使用 Path.GetFullPath 吗? - BoeseB
1个回答

16

你可以使用Environment.CurrentDirectory获得当前目录。

要将相对路径转换为绝对路径,可以执行以下操作:

var currentDir = @"D:\toto\titi\tata\";
var case1 = Path.GetFullPath(Path.Combine(currentDir, @"test.txt"));
var case2 = Path.GetFullPath(Path.Combine(currentDir, @".\..\..\test\test.txt"));
var case3 = Path.GetFullPath(Path.Combine(currentDir, @".\..\test\test.txt"));
var case4 = Path.GetFullPath(Path.Combine(currentDir, @".\..\..\..\test\test.txt"));
var case5 = Path.GetFullPath(Path.Combine(currentDir, @".\..\..\..\..\test\test.txt"));
var case6 = Path.GetFullPath(Path.Combine(currentDir, @"\\server\share\folder\test".TrimStart('\\')));

检查指定文件是否存在:

if (File.Exists(fileName))
{
  // ...
}

因此,要总结一下,如果我正确理解了你的问题,你可以重写你的方法成这样:

private void btnSearchFile_Click(object sender, EventArgs e)
{
  var currentDir = Environment.CurrentDirectory;
  var relPath1 = txtBoxSearchFile.Text.TrimStart('\\');
  var newPath = Path.GetFullPath(Path.Combine(currentDir, relPath1));
  if (File.Exists(newPath))
    txtBoxFoundFile.Text = newPath;
  else
    txtBoxFoundFile.Text = @"File not found";
}

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