i have a function which combine path. Example
My application is located in D:\toto\titi\tata\myapplication.exe
And I create a windows form application(c#) which solve the relative path based on the path of my application (D:\toto\titi\tata\myapplication.exe
).
I want to this this :
1)Path to resolve is test.txt => D:\toto\titi\tata\test.txt
2)Path to resolve is .\..\..\test\test.txt => D:\toto\test\test.txt
3)Path to resolve is .\..\test\test.txt => D:\toto\titi\test\test.txt
4)Path to resolve is .\..\..\..\test\test.txt => D:\test\test.txt
5)Path to resolve is .\..\..\..\..\test\test.txt => The path doesn't exist
6)Path to resolve is \\server\share\folder\test => get the corresponding path in the server
.
I use this method
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;
}
but i doesn't solve point 1);point 5) and point 6)
Can you help me
You can get the current directory with Environment.CurrentDirectory
.
To convert from relative paths to absolut paths you can do this:
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('\\')));
And to check the existance of a specified file:
if (File.Exists(fileName))
{
// ...
}
So to conclude you can rewrite your method to something like this (if I understand your question correctly):
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";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With