Reputation: 57
I have a functionality where I would scan a given path for a certain file and process some information based on the information in that file . this file info.json in json syntax has a name and a relative path to a certain directory . What I am trying to do is simply obtain the relative path from the json file and print out an absoulute path
the relative file specified in the info.json file is as below,
{
"Name": "testName",
"OriginalPath": "new/File"
}
The absolute path that I am trying to print out is something like :- D:\testDel\new\File
but the actual value is always something like D:\testDel\new/File
, while I must say this path is still a valid path (when I do a win key + R I can navigate to that directory) but in terms of how its been displayed it looks messy .
Any Idea as to why I might be facing this problem , am I doing something wrong ,
my code is as follows
string path = @"D:\testDel";
IEnumerable<string> foundFiles = Directory.EnumerateFiles(path, "info.json", SearchOption.AllDirectories);
foreach (string file in foundFiles)
{
DataModel data = JsonConvert.DeserializeObject<DataModel>(File.ReadAllText(file));
string Name = data.Name;
string absolutePath = data.OriginalPath;
string folderpath = Path.GetDirectoryName(file);
string fullPath = Path.Combine(folderpath, absolutePath);
Console.WriteLine(fullPath);
}
public class DataModel
{
public string Name { get; set; }
public string OriginalPath { get; set; }
}
Upvotes: 0
Views: 257
Reputation: 500
Wrap the Path.Combine(folderpath, absolutePath) statement in a Path.GetFullPath() as
fullPath=Path.GetFullPath(Path.Combine(folderpath, absolutePath));
this will also resolve reletive paths like ../NewFil
to D:\NewFile
Upvotes: 1
Reputation: 23228
You can update a path, coming from JSON using Replace
method and built-in Path.AltDirectorySeparatorChar
and Path.DirectorySeparatorChar
fields
string absolutePath = data.OriginalPath.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
string folderpath = Path.GetDirectoryName(file);
You are right, that path D:\testDel\new/File
is valid, because Windows supports both, forward slash and backslash
Upvotes: 1