I am trying to construct a file path in order to read an XSLT file, like so:
string path = "../_xslt/example.xslt";
StreamReader reader = new StreamReader(path);
...where I am in a controller (/Controllers/ExampleController.cs), and the '/_xslt/' folder is at the same level as '/Controllers'
However, the error I am getting is:
(System.IO.DirectoryNotFoundException)
Could not find a part of the path 'c:\windows\system32\_xslt\example.xslt'.
Am I going about this the wrong way?
Thanks for any help!
You can use the HttpServerUtility.MapPath method to map any relative paths for you, in your controller this is easily accessible via the ControllerContext:
string path = ControllerContext.HttpContext.Server.MapPath("~/_xslt/example.xslt");
...
string TestX()
{
string path = AppDomain.CurrentDomain.BaseDirectory; // You get main rott
string dirc = ""; // just var for use
string[] pathes = Directory.GetDirectories(path); // get collection
foreach (string str in pathes)
{
if (str.Contains("NameYRDirectory")) // paste yr directory
{
dirc = str;
}
}
return dirc; // after use Method and modify as you like
}
If controller is present at directory root
String path = ControllerContext.HttpContext.Server.MapPath(#"~/_xslt/example.xslt");
Else
String path = ControllerContext.HttpContext.Server.MapPath(#"../_xslt/example.xslt");
Related
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; }
}
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
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
I'm Currently inside a for loop which iterates through a set of folders and obtains some required values from a JSON file. I also want to get the absolute path to each of those files.
Currently I tried approaches such as
string currentDir = AppDomain.CurrentDomain.BaseDirectory; string
currentDir = Directory.GetCurrentDirectory();
Both of these gave me location to the debug file
what I want is the location of the Folder in which this file is existing rather .
Below is the code segment to which I hope to include this new code.
string rootDirectory = fbd.SelectedPath;
var foundFiles = Directory.EnumerateFiles(rootDirectory,
"server.config", SearchOption.AllDirectories);
foreach (var file in foundFiles)
{ RepositoryHomeSettingsModel repositoryHomeSettingsModel =
JsonConvert.DeserializeObject(File.ReadAllText(file));
string Name = SettingsModel.name;
}
Please find below possible ans,Do you require the same ?
var foundFiles = Directory.EnumerateFiles(rootDirectory, "*.txt", SearchOption.AllDirectories);
foreach (var file in foundFiles)
{
var folderpath= Path.GetDirectoryName(file);
//RepositoryHomeSettingsModel repositoryHomeSettingsModel = JsonConvert.DeserializeObject(File.ReadAllText(file));
//string Name = SettingsModel.name;
}
it is my path example E:\test\img\sig.jpg
I want to get E:\test\img to create directory
i try split but it be img
so I try function Directory.CreateDirectory and the path is E:\test\img\sig.jpg\
say me a ideas?
The recommended way is to use Path.GetDirectoryName():
string file = #"E:\test\img\sig.jpg";
string path = Path.GetDirectoryName(file); // results in #"E:\test\img"
Use Path.GetDirectoryName which returns the directory information for the specified path string.
string directoryName = Path.GetDirectoryName(filePath);
The Path class contains a lot of useful methods for path handling, which are more reliable than manual string manipulation:
var directoryComponent = Path.GetDirectoryName(#"E:\test\img\sig.jpg");
// yields `E:\test\img`
For completeness, I'd like to mention Path.Combine, which does the opposite:
var dirAndFile = Path.Combine(#"E:\test\img", "sig.jpg");
// no more checking for trailing slashes, hooray!
To create the directory, you can use Directory.Create. Note that it is not necessary to check if the directory exists first.
You can try this code to find the directory name.
System.IO.FileInfo fi = new System.IO.FileInfo(#"E:\test\img\sig.jpg");
string dirname = fi.DirectoryName;
and to create the directory
Directory.CreateDirectory(dirname );
Another solution can be :
FileInfo f = new FileInfo(#"E:\test\img\sig.jpg");
if (f.Exists)
{
string dirName= f.DirectoryName;
}
I have to create a directory and then a text file inside this directory with name come from parameter. E.g. _year is a parameter and I tried as:
var _root = "C:\\Users\\~\\DirichletProcessClustering\\Results";
var _clusterFilename = _year.ToString() + "cluster.txt";
var _path = Path.Combine(_root, _year.ToString(), _clusterFilename);
if(!Directory.Exists(_path))
{
Directory.CreateDirectory(_path);
}
// output topk file
TextWriter _twClus = File.CreateText(_path);
foreach (// loop )
{
_twClus.WriteLine("Cluster");
//... rest of the implementation...
}
This code is creating a folder named 2005 at specified path and then inside this folder, there is another folder named 2005cluster.txt while I want to create a text file named 2005cluster.txt inside folder 2005.
Where I am getting wrong in creating correct folder and file names?
An UnauthorizedAccessException generated at undermentioned line of
code i.e. access is denied. Why is this happening?
TextWriter _twClus = File.CreateText(_path);
Try this so that your path has a slash before the file name:
var _root = "C:\\Users\\~\\DirichletProcessClustering\\Results\\";
As you are defining fileName separately, You could try this:
var _root = "C:\\Users\\~\\DirichletProcessClustering\\Results";
var _clusterFilename = _year.ToString() + "cluster.txt";
var _path = Path.Combine(_root, _year.ToString());
if(!Directory.Exists(_path))
{
Directory.CreateDirectory(_path);
}
// output topk file
TextWriter _twClus = File.CreateText(Path.Combine(_path, _clusterFilename));
foreach (// loop )
{
_twClus.WriteLine("Cluster");
//... rest of the implementation...
}
Remove the file name from your path as:
var _path = Path.Combine(_root, _year.ToString());
For defining the filename you have to modify this line of code as:
TextWriter _twClus = File.CreateText(Path.Combine(_path, _clusterFilename));
I am using AppDomain.CurrentDomain.BaseDirectory and I want to go one step backwards but couldn't figure out how? Below is the example,
CODE :
string path = AppDomain.CurrentDomain.BaseDirectory;
RESULT :
"C:\\Mainline Code\\IxExpress\\.NET Applications\\IXTextIndexBuilder\\IXTextIndexBuilder\\bin\\Debug\\"
EXPECTED RESULT:
"C:\\Mainline Code\\IxExpress\\.NET Applications\\IXTextIndexBuilder\\IXTextIndexBuilder\\bin"
You can use something like the following to get the parent of a given directory:
string dirName = AppDomain.CurrentDomain.BaseDirectory; // Starting Dir
FileInfo fileInfo = new FileInfo(dirName);
DirectoryInfo parentDir = fileInfo.Directory.Parent;
string parentDirName = parentDir.FullName; // Parent of Starting Dir
Use following snippet:
string path = (new FileInfo(AppDomain.CurrentDomain.BaseDirectory)).Directory.Parent.FullName;
Directory.GetParent(AppDomain.CurrentDomain.BaseDirectory).Parent.FullName