Get Project Root Directory Name in MVC 5 - c#

I can't seem to find an answer anywhere on how to get the name of the first folder of my project.
So for Example I have a BaseSite folder and inside that BaseSite folder is where my solution file sits, in there I have many projects. I need to retrive the "BaseSite" name and only that.
I have found various examples with AppDomain.CurrentDomain.GetData("DataDirectory").ToString(); but that gives you the full path and my folder name is buried in there.
Same with: Server.MapPath("~/App_Data/somedata.xml");

Please check. It will return the base directory.
var BaseDirectory = new DirectoryInfo(Server.MapPath("~")).Parent.Name;
And
new DirectoryInfo(Server.MapPath("~/App_Data/somedata.xml")).Parent.Name;

I hope this will help you.
//this path will return current project folder
string path = AppDomain.CurrentDomain.BaseDirectory;
DirectoryInfo info = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory);
string infy = info.Parent.FullName; //this will give you the full path of project folder.
if you have to go one level up then add
info.Parent.Parent.FullName
And if you have to go one level down to subdirectory. Then use
DirectoryInfo[] directoryinfo = info.GetDirectories("SearchPattern or your subdirectory name");
string subdirectory = directoryinfo.FirstOrDefault().FullName;

Related

asp.net 404 - File or directory not found on website but locally it can

I have a folder "res/resx/" which contatins .resx files. What I want is to get all those .resx files.
Here is my code for that.
var Path = Server.MapPath("~/");
var SampleUrl = System.IO.Path.GetFullPath(System.IO.Path.Combine(Path, "Res/resx/"));
string[] files= System.IO.Directory.GetFiles(SampleUrl);
var AllFiles = new System.Collections.ObjectModel.ReadOnlyCollection<string>(files);
foreach (string sFileName in AllFiles)
{
Response.write(sFileName + " <br>");
}
This code is working on my local and i was able to see a list of my resx files. But when i deploy this to my website and access it, an error occurs on the 2nd line of code which says:
Could not find a part of the path
'D:\Websites\mywebsite.com\Res\resx'
I tried allowing directory browsing to see if my files exist. In my local, i can browse the files but on the website, I cannot. And it seems the system cannot find the folder "Res/Resx" too. it says:
404 - File or directory not found. The resource you are looking for
might have been removed, had its name changed, or is temporarily
unavailable.
But the folder exist and it is running on my local. Any advice as to what i should do or is their something i have missed? Thanks
Try this
string[] filePaths = Directory.GetFiles(Server.MapPath("Your folder"));
Look at the System.IO.Directory class and the static method GetFiles. It has an overload that accepts a path and a search pattern. Example:
string[] files = System.IO.Directory.GetFiles(path, "*.resx");
answered by
Anthony Pegram here.

How do i get a relative path of a file when running my code in debug for coded ui

I'm trying not to hard code my path, but I have not been able to figure our a way to get to an xml file that I have included in my project under a folder labeled Datasource. Here is my latest code that I have tried which still doesn't work.
public static string myAssemblyDirectory
{
get
{
string codeBase = Assembly.GetExecutingAssembly().CodeBase;
UriBuilder uri = new UriBuilder(codeBase);
string path = Uri.UnescapeDataString(uri.Path);
return Path.GetDirectoryName(path);
}
}
string fileName = xmlFileName;
string path = Path.Combine(myAssemblyDirectory, #"DataSource\" + fileName);
XmlDocument xDoc = new XmlDocument();
xDoc.Load(path);
Here is the output for the path that I'm getting which is putting it in my test results output folder.
"C:\MyAutomation\Automated_Test_Projects\AutomationProjects\MiserReleaseTestSuites\TestResults\marcw_ISD2005M 2016-02-05 10_15_17\Out\DataSource\Miser_Login_Dts.xml"
If possible I'd like to point it to
"C:\MyAutomation\Automated_Test_Projects\AutomationProjects\MiserReleaseTestSuites\MiserReleaseTestSuites\DataSource\Miser_Login_DTs.xml"
".." Can be used to go to the relative parent directory. "." Refers to the current directory.
You can combine these to form a relative path that starts higher up in the directory tree.
In your example you need to go 3 directories higher than the out folder and then into the MiserReleaseTestSuites\DataSource folder. Combining this produces
#"..\..\..\MiserReleaseTestSuites\DataSource\"
You can deploy the file in the same manner as you would when data driving the tests. See https://stackoverflow.com/a/25742114/546871
The TestContext class contains several fields with "directory" in their names. These can be used to access the various directories associated with running the tests. See also https://stackoverflow.com/a/19682311/546871

Getting the parentDirectory of a file in a unc path c# 2010

I need to identify first is this a UNCPath if so get the file directory
Is there a method to identify if a path is a UNC Path?
How do I get the file's parent.Parent.directory?
\\MyServer\\MySharedDrive\\MyDirectory\\MySubDirectory\\Myfile.csv
Wanted result and should work however deep
\\MyServer\\MySharedDrive\\MyDirectory
so that I can save another file to the above directory.
I guess I cannot do
Path.Combine("\\MyServer\\MySharedDrive\\MyDirectory",myNewFile.csv)
Any Suggestions?
Many thanks
To get parent directory and then creating a new path you can do:
string path = "\\MyServer\\MySharedDrive\\MyDirectory\\MySubDirectory\\Myfile.csv";
DirectoryInfo directory = new DirectoryInfo(Path.GetDirectoryName(path));
string finalPath = Path.Combine(directory.Parent.FullName, "myNewFile.csv"
To check if the path is UNC check this post.
From MSDN
Most members of the Path class do not interact with the file system
and do not verify the existence of the file specified by a path string
Again from MSDN on Path class
In members that accept a path, the path can refer to a file or just a
directory. The specified path can also refer to a relative path or a
Universal Naming Convention (UNC) path for a server and share name
Said that, you could write
string myUNCPath = #"\\MyServer\MySharedDrive\MyDirectory\MySubDirectory\Myfile.csv";
string myParent = Path.GetDirectoryName(Path.GetDirectoryName(myUNCPath));
string finalFile = Path.Combine(#"\\MyServer\MySharedDrive\MyDirectory","myNewFile.csv");
As a safety check you should execute two separate calls to Path.GetDirectoryName because if you have only one level deep of subdirectory then the result of Path.GetDirectoryName will be null
For example, if the initial UNC path is
string myUNCPath = #"\\MyServer\MySharedDrive\MyDirectory\Myfile.csv";
string myParent = Path.GetDirectoryName(myUNCPath);
if(!string.IsNullOrWhiteSpace(myParent))
{
myParent = Path.GetDirectoryName(myParent);
if(!string.IsNullOrWhiteSpace(myParent))
{
string finalFile = Path.Combine(myParent, "myNewFile.csv");
.....
}
}
For the part relative to your first question, the discovery of an UNC path is relatively easy.
See this article on Windows Dev Center about Paths and Files
Console.WriteLine(IsUNCPath(myUNCPath));
......
bool IsUNCPath(string pathToCheck)
{
return pathToCheck.StartsWith(#"\\");
}

How to copy a directory from local drive to a shared network using asp.net C#

Hello I am attempting to copy a directory and its subdirectories from my D drive to a shared network but I continue getting the error as
Exception:
Could not find a part of the path '/Projects/08.ASP.NETProjects/ProjectName/'.
My C# copy code:
System.IO.DirectoryInfo directory = new System.IO.DirectoryInfo(D drive path);
var destinationpath = "file:///BZ0025BZV43/Projects/08.ASP.NETProjects/ProjectName/";
var uri = new Uri(destinationpath);
var destinationurl = uri.AbsolutePath;
foreach (System.IO.FileInfo mydirectory in directory.GetFiles())
mydirectory .CopyTo(destinationurl);
I am new to FileHandlers. Please help.
Try to use uri.LocalPath instead of uri.AbsolutePath.
Also, be aware that you are trying to copy a file into a directory. But you have to copy the file into another file of that directory. (Directories are files too, basically).
So to do that check if the target directory exists and create it when necessary. Then replace .copyTo(destinationUrl) with .copyTo(Path.Combine(uri.LocalPath, mydirectory.Name)) and you should be good to go. And please rename the variable mydirectory to file or something similar.
Also note that you are not copying the directory tree recursively. So if you want to recurse the tree, you have to check for subdirectories and copy the files in that hierarchy, too.
You can also check out this example: http://msdn.microsoft.com/de-de/library/bb762914(v=vs.110).aspx

Ways to get the relative path of a folder

I have one folder named "Images" in my project. I want to get the path of the Image folder so that I can browse that and get the files.
I'm using below piece of code for my above requirement and it is working fine.
string basePath = AppDomain.CurrentDomain.BaseDirectory;
basePath = basePath.Replace("bin", "#");
string[] str = basePath.Split('#');
basePath = str[0];
string path = string.Format(#"{0}{1}", basePath, "Images");
string[] fileEntries = Directory.GetFiles(path);
foreach (string fileName in fileEntries)
listBox.Items.Add(fileName);
Just want to know like is there any elegant way of doing this? What are the best ways of getting the folder path?
This is what i usually use:
string appDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
Note that this returns the directory of the assembly that contains the currently executing code (i assume this is your main executable).
To get the parent directory of the resulting path, you can also use
Path.GetDirectoryName(appDirectory);
I would advice against depending on the Visual Studio project structure in your code, though. Consider adding the images folder as content to your application, so that it resides in a subdirectory in the same directory as your executable.
If you are just trying to reference a directory with a fixed relationship to another, then you can just use the same .. syntax you'd use at the command line?
You should also use the methods in the Path class (eg Path.Combine) rather than all that string manipulation.

Categories

Resources