Get the file path of current application's config file - c#

The reason I asked this question is that I wanted to create a helper class for Remoting instantiation, and wanted to pass the appropriate app.exe.config (or web.config) file path to the RemotingConfiguration.Configure method, depending on the caller.
Is there a way I could get the name of the config file for both Win and Web apps without checking if the application is Web or WinForms?

You can use the ConfigurationFile property on the SetupInformation for AppDomain.CurrentDomain.
This will get either the web.config or and app.config (yourprogram.exe.config) location.
AppDomain.CurrentDomain.SetupInformation.ConfigurationFile

I've used
string folder = System.Web.HttpContext.Current != null ?
System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "App_data") :
System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
without problems, but maybe there is some corner cases I don't know about...

To find the location of executing application
System.Reflection.Assembly.GetExecutingAssembly().Location;
Don't know about web case.

Related

targeting file using relative path on mvc app

I want to access to the file on my web project under content folder, and I want to use relative path. Can someone confirm me that I'm using right approach
string file = System.Web.Hosting.HostingEnvironment.MapPath("~/Content/myfile.txt");
yes its 100% right.
When you execute the code outside the context of a http request then HttpContext.Current is null and your code crashes. HostingEnvironment.MapPath always works
In this scenario i have used this approach to get multiple files and it worked fine ,so i recommend this .
try it once
String[] files = Directory.GetFiles(#HostingEnvironment.ApplicationPhysicalPath + "\\Videos\\");

call exe using Process without absolute path

I wrote a program need to call an external exe using
Process proc = Process.Start(filepath).
I specify the absolute path of the exe and it works fine. However, I need to use this program in different computers. Each time the exe has a different absolute path and I need to change the code for this part. I would like to know is there a way that I don't need to change the code? Thanks in advance!
You are asking the wrong question. Is not how to modify the API to work with your fixed requirements ("launch process w/o knowing the path", ignoring for a moment what huge security problem that is). The question you should ask is How can I modify my code to match the API I use?
Since starting a process works better if a full path is given (it also works if the executable name is in %PATH%, but that is a different topic), have you app figure out the correct path and then launch the process. There are countless ways to achieve this. Probably the safest option is to use an App.Setting that points to the path. At deployment the app is properly configured with the location of the required program. there are (many) more ways to do this, it will all depend on what you're actually trying to solve, more details would be needed.
If both exe-files are in the same folder, then
winforms:
var filepath = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), otherexename);
Process.Start(filepath);
wpf:
var filepath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, otherexename)
Process.Start(filepath);
In a windows service, you can do the following to get the directory of the currently running assembly, then to generate the right path to your exe:
var directory = Path.GetDirectoryName(
new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath);
var exeLocation = Path.Combine(directory,"myExe.exe");

Checking the existence of a file using relative path

What is the best way to check the existence of a file using relative path.
I've used the following method but it returns false despite the fact that file is existing.
bool a = File.Exists("/images/Customswipe_a.png");
That's not a relative path. You need to leave off the first / otherwise it will be interpreted as being rooted (i.e. C:/images...)
I guess that you are running this code in asp.net application, thats why you get false.
In asp.net you should use Server.MapPath("/images/Customswipe_a.png") to get "correct" path (relative to the web application root directory). Otherwise you get path local to the webserver executable (IIS/WEBDAV/..name any other).
The relative path is relative to the current working directory. It may not be the application directory. Call GetCurrentDirectory() to check the actual path you are testing.
You just need to define what your file is relative to
Your application main assembly?
Current directory?
Application data directory?
name it...
In each of these cases I'd suggest you to convert it into an absolute path by Path.Combine method:
public static readonly string AppRoot = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
...
//calling with a '/' heading makes the path absolute so I removed it
var fullPath = Path.Combine(AppRoot, "images/Customswipe_a.png");
var exists = File.Exists(fullPath);
This way you can guarantee where you are looking for. Even the Open/Save file dialogs may change your current directory. So, calling File.Exists without full path is usually a wrong decision.
You can test this path with System.IO.DirectoryInfo:
DirectoryInfo info = new DirectoryInfo("/images/Customswipe_a.png");
string absoluteFullPath = info.FullName;
As Mike Park correctly answered this path is likely to be (i.e. C:/images...)
The relative path, is a relative to something.
In this API, it will, according to the documentation File.Exists:
Relative path information is interpreted as relative to the current
working directory.
So everything here is depends what is CurrentDirectoty at the moment of execution of this query.
Plus, your path is not valid Desktop path (I assume you pick it from some web file, or knowledge). To understand if specified path contains not valid characters use GetInvalidCharacters function.
In your specific case it would be enough to use #"\images\Customswipe_a.png".
The path is relative to the location of your binary file. In the case of a visual studio project, this would be %PROJECTDIR%/bin/(RELEASE||DEBUG)/
What I would do is put the filesystem root in a config file, and use that for your relative path.
In a WinForms application you can get the directory of the exe file with
string directory =
Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath);
Another solution uses Reflection
string directory =
Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
As of .NET Core 3.1, this works:
Use dependency injection to include service IWebHostEnvironment
private IWebHostEnvironment Env;
public MyController (IWebHostEnvironment env){
Env = env;
}
Then use it to get path to root of app with Env.ContentRootPath
And combine it all:
var file = System.IO.Path.Combine(Env.ContentRootPath, "images", "some-file.png");

full path of a folder in c#

i need to get the full folder path in a windows project using c#.I tried with path.getFulPath(filename).bt it returns the application path+filename.how can i get the actual path like "D:\eclipse_files\ads_data"?
A relative path such as myfile.txt is always resolved in relation to the current working directory.
In your case the current working directory seems to be D:\eclipse_files\ads_data so your relative file path gets resolved to D:\eclipse_files\ads_data\myfile.txt when you call Path.GetFullPath.
To solve the problem, either make sure that you start with an absolute path from the beginning, or, that your working directory is set correctly.
You can get/set the working directory using the Directory.GetCurrentDirectory and Directory.SetCurrentDirectory methods.
Your question is not very clear, but I think you're looking for this:
string path = Path.GetDirectoryName(filename);
If I have understood correctly, you have a filename, for example 'doc.txt', and you want to have a method to return the full path of this file regardless of where the application runs from?
If this is what you ask it is not possible. Have you considered that there might be several files called 'doc.txt' on your harddrives?
The best you can hope to do it to search all harddrives, and return a list of all files found with the same name, but that will just be ridicously slow.

ASP.NET Relative Paths in Referenced Libraries

I have an ASP.NET website in which I am loading some validation rules from an xml file. This xml file name, with no path info, is hard coded in a library. (I know that the hard coded name is not good, but let's just go with it for this example).
When I run the website, ASP.NET tries to find the xml file in the source path, where the C# file in which name is hard coded is. This is completely mind boggling to me, as I can't fathom how, at runtime, we are even considering a source path as a possibility for resolving an unqualified filename.
// the config class, in C:\temp\Project.Core\Config.cs
public static string ValidationRulesFile {
get { return m_validationRulesFile; }
} private static string m_validationRulesFile = "validation_rules.xml";
// using the file name
m_validationRules.LoadRulesFromXml( Config.ValidationRulesFile, "Call" );
Here is the exception showing the path we are looking in is the same as Config.cs:
Exception Details: System.IO.FileNotFoundException:
Could not find file 'C:\temp\Project.Core\validation_rules.xml'.
Can anyone explain this to me? I already know how you are supposed to handle paths in general in ASP.NET so please don't respond with solutions. I just really want to understand this, since it really surprised me, and It is going to bother me to no end.
UPDATE
Here is the relevant code for LoadRulesFromXml
public void LoadRulesFromXml( string in_xmlFileName, string in_type )
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load( in_xmlFileName );
...
UPDATE2
It looks like the Cassini web server gets its current directory set by VS, and indeed it is set to the path of my library project. I'm not sure exactly how VS determines which project to use for the path, but this at least explains what is happening. Thanks Joe.
If you don't supply a path, then file access will normally use the current working directory as the default. In ASP.NET this is probably your web application directory.
It's not usually a good idea to rely on the current working directory, so you can use Path.Combine to specify a different default directory, e.g. one relative to AppDomain.CurrentDomain.BaseDirectory, which is also the web application directory for an ASP.NET app.
You should add the path explicitly to the name of the file you're opening. You could also try tracing the current working directory.
When running Cassini from Visual Studio, the current directory is inherited from whatever happens to be Visual Studio's working directory: this seems to be your case.
I.e.:
public void LoadRulesFromXml( string in_xmlFileName, string in_type )
{
// To see what's going on
Debug.WriteLine("Current directory is " +
System.Environment.CurrentDirectory);
XmlDocument xmlDoc = new XmlDocument();
// Use an explicit path
xmlDoc.Load(
System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
in_xmlFileName)
);
...
At a complete guess I would say that the Method LoadRulesFromXml() is looking at the path of the Application Root URL for where the site is hosted... which is C:\temp\Project.Core\
probably by doing a Server.MapPath("~")
Can you post the code for LoadRulesFromXML or do you have that code ?

Categories