我有一个结合路径的函数。例子
我的应用程序位于 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;
}
Run Code Online (Sandbox Code Playgroud)
但我没有解决第 1) 点;第 5) 点和第 6) 点
你能帮助我吗
您可以使用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('\\')));
Run Code Online (Sandbox Code Playgroud)
并检查指定文件的存在:
if (File.Exists(fileName))
{
// ...
}
Run Code Online (Sandbox Code Playgroud)
因此,总而言之,您可以将您的方法重写为这样的方法(如果我正确理解您的问题):
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";
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4778 次 |
| 最近记录: |