Old question, but still relevant 15 years later in .Net Core 8 VS2020 (v 17.4)
...I want relative path so that if I move my solution to another system the code should not effect.
please suggest how to set relative path
Starting with F:\temp\r.cur
(more fun than F:\r.cur
)
string p = @"F:\temp\r.cur";
Console.WriteLine($"1. p == '{p}'");
// Change this to a relative path
if (Path.IsPathRooted(p))
{
// If there is a root, remove it from p
p = Path.GetRelativePath(Path.GetPathRoot(p), p);
Console.WriteLine($"2. p == '{p}'");
}
// Combine the relative directory with one of the common directories
Console.WriteLine($"3. p == '{Path.Combine(Environment.CurrentDirectory, p)}'");
Console.WriteLine($"4. p == '{Path.Combine(Environment.ProcessPath ?? "", p)}'");
Console.WriteLine($"5. p == '{Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), p)}'");
Console.WriteLine($"6. p == '{Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), p)}'");
Output:
1. p == 'F:\temp\r.cur' Starting place
2. p == 'temp\r.cur' Stripped of the root "F:"
3. p == 'D:\Code\scratch\temp\r.cur' Current Directory
4. p == 'D:\Code\scratch\bin\Debug\net8.0\testproject\temp\r.cur' Process Path
5. p == 'C:\Users\jcc\AppData\Local\temp\r.cur' Local Application Data
6. p == 'C:\Users\jcc\AppData\Roaming\temp\r.cur' Application Data (roaming)
If you only want the file name, that's a lot easier:
//if you ONLY want the file name, it is easier
string fname = Path.GetFileName(@"F:\temp\r.cur");
// Combine the relative directory with one of the common directories (the current directory, for example)
Console.WriteLine($"3. fname == '{Path.Combine(Environment.CurrentDirectory, fname)}'");
Console.WriteLine($"4. fname == '{Path.Combine(Environment.ProcessPath ?? "", fname)}'");
Console.WriteLine($"5. fname == '{Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), fname)}'");
Console.WriteLine($"6. fname == '{Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), p)}'");
Since you're here... these path manipulations may also be of interest -
Console.WriteLine($"1 Given path: \"D:\\Temp\\log.txt\"");
Console.WriteLine($"2 file name '{Path.GetFileName(@"D:\Temp\log.txt")}'");
Console.WriteLine($"3 no ext '{Path.GetFileNameWithoutExtension(@"D:\Temp\log.txt")}'");
Console.WriteLine($"4 only ext '{Path.GetExtension(@"D:\Temp\log.txt")}'");
Console.WriteLine($"5 dir name '{Path.GetDirectoryName(@"D:\Temp\log.txt")}'");
Console.WriteLine($"6 full path '{Path.GetFullPath(@"D:\Temp\log.txt")}'");
Output:
1 Given path: "D:\Temp\log.txt"
2 file name 'log.txt'
3 no ext 'log'
4 only ext '.txt'
5 dir name 'D:\Temp'
6 full path 'D:\Temp\log.txt'