Get Application File Path in Windows Forms Application - asp.net

I have a simple windows form app that I need to get the file path for. I am placing a config file in the same directory and I need to be able to get the path to that file.
I have used
Application.CommonAppDataPath
but that returns the path with 1.0.0.0 at the end.
and
Applicaiton.StartupPath
but that returns the path with \bin\debug at the end
Is there anyway to get the path to just the main file directory without anything appended to the end?

Application.StartupPath is returning the path with \bin\debug on the end because that is where your code is running, at least on your development machine.
If you are going to deploy this away from your development machine then Application.StartupPath will give you what you're asking for - the file path for your application. And yes, if you have deployed the config file to that same location, your code is going to find it.
How to get the application also working on your development machine and get round the bin\debug issue? Well, a dirty hack would be just to chop the bin\debug string off the end of Application.StartupPath.
In that case, if you need to check for whether you're running inside the debugger, see this question

Try with
Dim aPath As String
Dim aName As String
aName = _
System.Reflection.Assembly.GetExecutingAssembly. _
GetModules()(0).FullyQualifiedName
aPath = System.IO.Path.GetDirectoryName(aName)

You can use
Application.ExecutablePath; which gives full path including executable file name
and
Application.StartupPath; for your current running application path directory without file name

Related

Load Report Failed (Invalid Report File Path)

I have old Asp.net web application (Visual Studio 2005) deployed in Windows Server 2012 and it runs for years. Now, we are encountering "Load report failed - Invalid Report File Path" error. Then I checked the code if the .rpt file has correct path and the actual .rpt file is already in the web server and yet, it was there. Ever since we are encountering this error, we just recycling the App pool of the application in IIS and the app runs smoothly again.
Any ideas on how this issue prevent from recurring?
Here's the snippet of my code:
reportPath = Server.MapPath("~\crm-DailyActualSalesCompressed.rpt")
pReportDoc.Load(reportPath)
pReportDoc.SetDatabaseLogon(myConInfo.UserID, myConInfo.Password, myConInfo.ServerName,
myConInfo.DatabaseName)
As the error message said you are wrong on your path, this backslash ”\” is for physical path and this slash “/” is for relative url’s which needs to mapped by Server.
So in order to read your CR file you can do that in two ways that depends on your pReportDoc what kind of Object/type is:
If is a backend object you can do that:
reportPath = Request.PhysicalApplicationPath & "crm-DailyActualSalesCompressed.rpt"
pReportDoc.Load(reportPath)
pReportDoc.SetDatabaseLogon(myConInfo.UserID, myConInfo.Password, myConInfo.ServerName, myConInfo.DatabaseName)
If pReportDoc is a kind of WebControl or something elese you can do that:
reportPath = Server.MapPath("~/crm-DailyActualSalesCompressed.rpt")
pReportDoc.Load(reportPath)
pReportDoc.SetDatabaseLogon(myConInfo.UserID, myConInfo.Password, myConInfo.ServerName, myConInfo.DatabaseName)
Obviously you need to know also if you CR file is on root (as seems) or included in other nested paths

How to save generated file temporarily in servlet based web application

I am trying to generate a XML file and save it in /WEB-INF/pages/.
Below is my code which uses a relative path:
File folder = new File("src/main/webapp/WEB-INF/pages/");
StreamResult result = new StreamResult(new File(folder, fileName));
It's working fine when running as an application on my local machine (C:\Users\userName\Desktop\Source\MyProject\src\main\webapp\WEB-INF\pages\myFile.xml).
But when deploying and running on server machine, it throws the below exception:
javax.xml.transform.TransformerException:
java.io.FileNotFoundException
C:\project\eclipse-jee-luna-R-win32-x86_64\eclipse\src\main\webapp\WEB INF\pages\myFile.xml
I tried getServletContext().getRealPath() as well, but it's returning null on my server. Can someone help?
Never use relative local disk file system paths in a Java EE web application such as new File("filename.xml"). For an in depth explanation, see also getResourceAsStream() vs FileInputStream.
Never use getRealPath() with the purpose to obtain a location to write files. For an in depth explanation, see also What does servletcontext.getRealPath("/") mean and when should I use it.
Never write files to deploy folder anyway. For an in depth explanation, see also Recommended way to save uploaded files in a servlet application.
Always write them to an external folder on a predefined absolute path.
Either hardcoded:
File folder = new File("/absolute/path/to/web/files");
File result = new File(folder, "filename.xml");
// ...
Or configured in one of many ways:
File folder = new File(System.getProperty("xml.location"));
File result = new File(folder, "filename.xml");
// ...
Or making use of container-managed temp folder:
File folder = (File) getServletContext().getAttribute(ServletContext.TEMPDIR);
File result = new File(folder, "filename.xml");
// ...
Or making use of OS-managed temp folder:
File result = File.createTempFile("filename-", ".xml");
// ...
The alternative is to use a (embedded) database or a CDN host (e.g. S3).
See also:
Recommended way to save uploaded files in a servlet application
Where to place and how to read configuration resource files in servlet based application?
Simple ways to keep data on redeployment of Java EE 7 web application
Store PDF for a limited time on app server and make it available for download
What does servletcontext.getRealPath("/") mean and when should I use it
getResourceAsStream() vs FileInputStream
just use
File relpath = new File(".\pages\");
as application cursor in default stay into web-inf folder.

File Not found in exe of wpf application

When publishing the WPF application and generate an exe, I am unable to get the files which are placed in the templates-folder. When I copy my folder and files to bin it works, or if use
string StartUpPath = AppDomain.CurrentDomain.BaseDirectory.ToString();
// var gparent = Directory.GetParent(Directory.GetParent(Directory.GetParent(StartUpPath).ToString()).ToString()).ToString();
ReportDocument reportDocument = new ReportDocument();
StreamReader reader = new StreamReader(new FileStream(StartUpPath + #"\Templates\Invoice.xaml", FileMode.Open));
This code works fine for my local, but when I generate an exe, these files are not found.
That's because your files aren't in the exe. I had the same problem recently.
It sounds like you need to handle your resources - there are several ways to go about this, and Microsoft has a full explanation here about resources, including the difference between using Linked and Embedded Resources, and links through to other great guides.
I'm assuming you're using Visual Studio, in which case this should work;
right click the file you can't access
select properties (or press ALT + ENTER)
set Build Action to be Resource
set Copy to Output Directory to be Copy if newer
save
... and you should be good to go.
I think it throws an exception because the file doesn't exist on that machine. You can set Build Action to Content and Copy to Output Directory to Copy Always or Copy If Newer on property window.
These settings will make sure that you have the file to your output.

c# get path for directory in project

I'm trying get the path of a folder in my project called EmailAttachments. I tried
File.Exists("~/EmailAttachments/TestReport.pdf")
but that returns false. How can I get the path to a directory in the program so I can write files to it and retrieve them later?
This is in asp.net, not winforms
If you're trying to get the ASP.NET local path, use Server.MapPath("~/EmailAttachments/TestReport.pdf") to get its fully qualified path.

SubSonic connection string for SQLite

I'm writing a desktop app which needs a simple persistence layer - I found out about SubSonic and it's capability to work with SQLite. However I need to keep the database file in user's AppData folder and don't know how to put such value into app.config - I don't want to use absolute paths.
Can app.config somehow access enviroment variables or reference application data folder?
For subsonic v2.x I would ignore the app.config connection string and just set it at runtime before working with the database. The provider name stays the same of course.
string dbPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), #"MyApplication\Northwind.db3");
DataService.Providers["Northwind"].DefaultConnectionString =
String.Format(#"Data Source={0};Version=3;New=False;Connection Timeout=3", dbPath);
There's no way to specify the AppData folder in the app.config for a connections string.
But what you could do is write the value to the config file either during install or when the application is first run.
The "framework way" of finding appdata is to use Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
This will find the correct appdata path regardless of platform.
There are several ways if you are using ASP.NET , in either language
Server.MapPath("~") will return the root of the application as a full path name then you can just add "/app_data" to it to get you're full path.
Alternatively inspect the HttpContext.Current.Request and HttpContext.Current.Application
there are numerous ( and much better then the one I just mentioned ) properties that will provide you with the same folder - being the root of the application as s full path.
Note that these should all work even if you have the application as a virtual folder and a regular folder with an application configures in IIS on that folder
However this is only possible at runtime , so it can't really be mentioned in the app.config. you could try using relaltive paths from where the app.config is resident IE "../App_Data" or "/App_data" but I'm not sure of you're exact requirements.
Good luck

Resources