2015-02-09 30 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"; 
}