IIS 7 how to load assembly from Bin folder - c#

In .NET solutions I use custom classes for translations.
Main idea of translation framework
that files with translations are placed in folder near assembly.
All work fine when it calles from windows forms application.
But it does not work when I call it from web service...
I debug web service via Visual Studio 2010 and via bult-in debugger.
And I see that buit-in ASP.NET Developpment loades assemply from
C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\
and there is no possibility to find my folder with translations...
So suggest please what to do in this case?
I tested under IIS7 it does not work also.
sample code how I load assembly:
if (languageSettings == null)
{
TraceIt(assembly.Location);
string strPath = Path.Combine(Path.GetDirectoryName(assembly.Location), "Language.config");
TraceIt(strPath);
languageSettings = new LanguageSettings(strPath);
if (!languageSettings.LoadSettings())
{
languageSettings.CurrentLanguage = DefaultLocale;
languageSettings.SaveSettings();
}
}

In web environment, its usual to setup a key in web.config with the absolute path to your language data folder, instead of rely on lookups in execution folder:
<appSettings>
<add key="Languages" value="D:\Data\Languages" />
</appSettings>
and, in code
stirng path = ConfigurationManager.AppSettings["Languages"]
if (!String.IsNullOrEmplty(path))
{
string file = Path.Combine(path, filename);
// and so on...
}

In a web application, your assemblies will be located in a bin folder. Assuming your config file is one level up, at the root of your application, you can get its path using Server.MapPath, like this (You'll need to reference System.Web).
string strPath = HttpContext.Current.Server.MapPath("~/Language.config");

You could try and get the location from the type. For example:
string strPath =
Path.Combine(
Path.GetDirectoryName(typeof(LanguageSettings).Assembly.Location),
"Language.config");

Take a look at the solution given by John Sibly :
How do I get the path of the assembly the code is in?
i think this is more what you are looking for ;) as it work in both cases (win and web)

Related

C# get current directory without having to specify full path? [duplicate]

We have a web application written in ASP.NET 3.5. In it, we access a file in the code-behind. (Ordinary C# file access, done on the server during the page life-cycle, this has nothing to do with URLs or web browsers).
On our production systems, we specify the full path to the file in question in the web.config. We'd like to be able to include a local copy of the file in the project in version control, and then to use a relative path in the version-controlled web.config to point to it, so that a checked-out copy of the application could be run from within Visual Studio's debugger without having to do any configuration.
The problem is that when the web application is running in debug mode, its working directory is neither the project nor the solution directory. In a windows or console application, in a project's properties page I can set the working directory. But in a web application I cannot.
Any ideas on how I can manage to make this work?
To get the path of the root of the application:
//equivalent to Server.MapPath("/"); if at domain root, e.g Http://mysite.com/
string path = Server.MapPath("~");
This answer gives a rundown of a few different common Server.MapPath() uses that may also be of use to you.
In code behind: HttpContext.Current.Server.MapPath("~")
Use:
Server.MapPath("~");

Store XSD inside WCF webservice

Im developing a WCF web service with receives always and only XML.
So i need to validate that input XML using their XSD. The question is, can i save them inside web service? Locally i can access XSD files via relative path into IIS Express root folder which i created manually. I tried add the XSD files in VS project but i just cant a find them on runtime.
I'm using the Shemas like this: Image1 Link
IIS XSD'd Folder Path Workaround: Image2 Link
At the moment, its working fine, the problem will be when i try deploy the service somewhere on internet.
Thank you.
tl;dr: Can i send some XSD when deploying the webservice or its just impossible?
Files that belong to your solution should be physically part of it. Once that is the case you can use for instance HostingEnvironment.MapPath; or look at the answers to this question. Note that there is a possible issue with HostingEnvironment.MapPath when the WCF service is self hosted.
A possible solution is this method:
public static string MapPath(string path)
{
if (HttpContext.Current != null)
return HttpContext.Current.Server.MapPath(path);
return HostingEnvironment.MapPath(path);
}
The parameter path needs to be of the format "~/XSD/MyFile.xsd", with the folder "XSD" being located in the root of your WCF service.
NEVER create folders in c:\program files (x86)\iis express.
You can add the XSD as a resource, then load it from your assembly. Add the XSD to your project, and under the "Properties Explorer", set the "Build Action" to "Embedded Resource". You can then read the file with:
var schemaSet = new XmlSchemaSet();
schemaSet.Add("", XmlReader.Create(typeof(SomeClassInTheSameAssembly).Assembly
.GetManifestResourceStream("Full.Namespace.XsdName.xsd")));
See Working with Embedded Resources or Loading XmlSchema files out of Assembly Resources for more.
One way you can do it is by using an application setting in your config file that will hold a base file location such as:
<appSettings>
<add key="BaseDir" value="C:\your\folder\names" />
</appSettings>
Then in your program, when you need a file, you would do something like this:
string fileLocation = System.Configuration.ConfigurationManager.AppSettings["BaseDir"] +
#"\your\file\location\file.xsd";
To use System.Configuration.ConfigurationManager, you will need to add a reference to System.Configuration.

Get resources folder path c#

Some resources I have in my project are fine and working Ok using string paths but what if I move the project to another directory or to another computer, it will stop working.
Please I need to get the path of the resources folder of my project in a string variable,
Something like this
C:\Users\User1\Documents\<projects folder>\<project name>\Resources\
Thanks in advance.
If you know the path relative to where the app is running, you can do something like this.
First, get the app's running path:
string RunningPath = AppDomain.CurrentDomain.BaseDirectory;
Then, get navigate to the relative path using something like this:
string FileName = string.Format("{0}Resources\\file.txt", Path.GetFullPath(Path.Combine(RunningPath, #"..\..\")));
In this example I my "Resources" folder is located two directories up from my running one.
I should also mention, that if your resource is included in the project, you should be able to get it using:
System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceNames();
this will return an array of your resources.
If the files are stored in your project folder, you can retrieve the files using
System.AppDomain.CurrentDomain.BaseDirectory.
This statement retrieves the path as to where your application is installed.
Click Here to get a detailed explanation on this.
This might not be the cleanest way, but it has been useful to me.
If you had a structure like:
C:\...\MyApp\app.exe
C:\...\MyApp\ConfigFiles\MyConfig.xml
The code will return a path relative to the running assembly.
GetPath("ConfigFiles/MyConfig.xml") // returns the full path to MyConfig.xml
private string GetPath(string relativePath)
{
var appPath = System.Reflection.Assembly.GetExecutingAssembly().Location;
string pattern = #"^(.+\\)(.+exe)$";
Regex regex = new Regex(pattern, RegexOptions.None);
var match = regex.Match(appPath);
return System.IO.Path.GetFullPath(match.Groups[1].Value + relativePath);
}
You could try to use |DataDirectory| documented here.
Here's a description of how it works from an old Microsoft article
One of the reasons why it was hard to work with database files before
is that the full path to the database was serialized in different
places. This made it harder to share a project and also to deploy the
application. In this version, the .NET runtime added support for what
we call the DataDirectory macro. This allows Visual Studio to put a
special variable in the connection string that will be expanded at
run-time. So instead of having a connection string like this:
"Data Source=.\SQLExpress;AttachDbFileName=c:\program files\app\data.mdf"
You can have a connection string like this:
"Data Source=.\SQLExpress;AttachDbFileName=|DataDirectory|\data.mdf"
This connection string syntax is supported by the SqlClient and OleDb
managed providers.
By default, the |DataDirectory| variable will be expanded as follow:
- For applications placed in a directory on the user machine, this will be the app's (.exe) folder.
- For apps running under ClickOnce, this will be a special data folder created by ClickOnce
- For Web apps, this will be the App_Data folder

C# + File.OpenRead(path_to_file)

I am developing a HTML5 based WebApp being hosted in IIS7. This webapp sends requests to webservices being hosted in IIS7.
The service initialization looks up for a specific file e.g: "appfile.txt" as
FileStream stream = File.OpenRead("appfile.txt"); // opens file for reading.
This call when run as a console application looks up in the project\bin or output directory and able to locate the specified file.
But the same hosted in IIS7 looks up in "C:\windows\system32\inetsrv\appfile.txt".
Are there any configuration item having used in web.config locates the file from the Bin directory of the IIS7 application and not anywhere else?
Any help is much appreciated.
If the app file is in your web application folder, try using Server.MapPath to get The location of the file relative to the root of the web app:
File.OpenRead(Server.MapPath("~/appfile.txt"))
That should work. You probably need to set up the appfile.txt properties so it is copied to the output folder.
You can certainly create your own section in the web.config file to grab the file path that you want. It doesn't need to have been predefined. Then just use any XML reader you want.
Alternatively, you can make a .resx file very easily in Visual Studio and just populate the path there as a variable.
Thanks for all your valuable comments, I could resolve this issue myself using the following code snippets
string path = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath;
string[] labs = File.ReadAllLines(path + "/appfile.txt");
This bit of code allows me to read the file contents without any issues.

How to get to app-relative subdirectory in .net windows app?

I have an application that contains a sub folder that contain xml file ,that is use as a database now i want take the path of the xml file at run time ,how can i achieve this in window application?
I know how it does in asp.net using Server.MapPath but i want this is same in windows application
please help
thanks in advance .
Use Aplication.ExecutablePath property when am XML document and executable are reside in the same directory.
I think the recommended way in Windows is to use the Application.StartupPath property.
And with Path.Combine you can have your xml file path Server.MapPath-style like this:
var appPath = Application.StartupPath;
var xmlPath = Path.Combine(appPath, "data/my_db.xml");
// xmlPath now points to app-relative data/my_db.xml file
...
A nuanced answer:
The best way to access data would be to put it in Application.CommonAppDataPath or Application.UserAppDataPath so that it does not depend on the application's installed path. However, there are many reasons why you might need to avoid this.
To answer your question:
If the application is a standard forms application deployed to the client's machine by an installer or XCopy deployment, then the path to the executable is Application.ExecutablePath
If the application is Click-Once deployed, then I would not recommend using the above since the app's path is obscured, shadow-copied and put in the sandbox. You can use ApplicationDeployment.IsNetworkDeployed to test for click-once deployment then ApplicationDeployment.CurrentDeployment.ActivationUri to get the URI that the application was launched from. Your app-relative file will be on that web server; you will always be able to download it.
of course in click-once deployent it would be better to tag the file as Data in which case it would be accessible through ApplicationDeployment.CurrentDeployment.DataDirectory
if the application is a web app, then the Application class is useless. In this case you should use Assembly.GetExecutingAssembly().Location This works because currently executing assembly for a web app is almost always in the web app's /bin directory.
For a "portable" assembly where you don't have an installer, and for rare cases where you don't want to use the Application class, use Assembly.GetEntryAssembly().Location This works because it figures out what the entry point assembly is (your application) and uses that location. This is reliable because assemblies that your entry assembly load don't have to be in the same directory as the entry assembly.
You can get the directory of the currently executing assembly using
System.Runtime.Reflection.Assembly.GetExecutingAssembly().Location
from there you can get to your subdirectory.

Categories

Resources