2015-02-09 31 views
0

我有一个组合路径的函数。 实施例如何在c中解析相对路径#

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

我创建视窗形式应用(C#),其解决基于我的应用程序(D:\toto\titi\tata\myapplication.exe)的路径上的相对路径。

我想这样的:

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 => The path doesn't exist

6)解决的途径是\\server\share\folder\test => get the corresponding path in the server

我用这个方法

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&Serv er.MapPath :) – Icepickle 2015-02-09 13:54:04

+0

难道你不能使用Path.GetFullPath? – BoeseB 2015-02-09 13:55:00

回答

3

你可以得到当前目录与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"; 
}