我有一个组合路径的功能。 实施例
我的申请位于D:\toto\titi\tata\myapplication.exe
我创建了一个Windows窗体应用程序(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点
你能帮助我吗
答案 0 :(得分:4)
您可以使用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";
}