targeting file using relative path on mvc app - c#

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\\");

Related

Dealing with files in ASP.NET MVC

Im working on an ASP.NET MVC project that compiles input code to .exe file. Then, my code run this .exe. After success, I just delete that .exe file.
To relaese input code I'm using CSharpCodeProvider class. To run it, I'm using Process class.
Making and deleting exe files seems a little bit tricky to me, because I can't save that files into project directory directly while I'm debugging my program. I need to give special permissions to IIS_USERS. But what to do, when I want to release my project into production? How to deal with filepath? Where to save it?
Now, it looks like this:
string exeName = Path.Combine("C:\\Users\\User\\source\\repos\\proj\\solution\\obj\\Debug", "test.exe");
To deal with paths you should be using Server.MapPath("~") - This returns the physical Path to the root of the web application.
For example if you have a folder called "MyOutput" in the solution (in parallel to the Controller, Views etc. folders) then you can write Server.MapPath("~/MyOutput/"). This will resolve to a physical path like C:\Users\User\source\repos\proj\solution\MyOutput\
This way you do not have to bother about changing paths in local machines or web servers.
Also you should not be putting stuffs in the Obj or Bin folders which are not directly related to the web application.
More samples are available here: Server.MapPath("."), Server.MapPath("~"), Server.MapPath(#"\"), Server.MapPath("/"). What is the difference?
How about asking user where to save it?
You could have a form that ask for this path, username, password etc. Or even in a config <appSettings></appSettings>
Then you can use Impersonate to save it, execute it without any permission issue. You could use this to save it locally or to any network drive

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");

Why am I getting a "Could not find a part of the path" exception?

I am developing website using Visual Studio 2010. I am trying to save a file in a path. It works fine localhost.
But the same code is not working in IIS. It shows the following error
Exception Details: System.IO.DirectoryNotFoundException: Could not
find a part of the path 'C:\Inetpub\wwwroot\Vendor\cn.jpg'.
Could not find a part of the path 'C:\Users\shashank\Desktop\ab.csv'.
Here is the code:
protected void btnImportFile_Click(object sender, EventArgs e)
{
sArReportText = File.ReadAllText(txtFilePath.Text.Trim());
// Set the report Properties to insert Report information
SetProperties();
}
You might also be experiencing what I am: that the directory name contains some unusual characters. In my case,
Could not find a part of the path 'C:\Web\metBoot\wild iis\DigiCert© Certificate Utility for Windows_files'.
That copyright sign is the issue.
So using concepts drawn from Obtaining the short 8.3 filename from a long filename, I convert my paths to short form first, then use that to get my list of files.
StringBuilder sf = new StringBuilder(300);
int n = GetShortPathName(sourceFolder, sf, 300);
if (0 == n)
{
tk.write(Marshal.GetLastWin32Error().ToString());
continue;
}
...
IEnumerable<string> fileGroup = Directory.EnumerateFiles(sf.ToString(), ext);
Consider how you're launching VS too. Counter-intuitively I run into this problem only when I'm running VS in Administrator mode. Possibly a group policies thing.
This may be because, you are not having the specified file in web server, or you may be used an incorrect path. Specify the exact folder and filename as how it is stored in the web server. use HttpContext.Current.Request.ApplicationPath or Server.MapPath to specify the correct location where your desired file lies. And also make sure that you have given read and write permissions for this specific file and its folder.
You need to have permissions set in iis to allow files to be saved in the folder. Basically your uploaded files should be saved inside a separate folder present inside your root directory.
In order to access, create and delete files on the server, must have rights.
Like in my project I am using Impersonator class to access various files and folder from the server.
Otherwise it will throw an exception.
You could use code impersonation:
http://csharptuning.blogspot.com/2007/06/impersonation-in-c.html
http://www.codeproject.com/Articles/14358/User-Impersonation-in-NET
regardless, whomever you use as the impersonation must be able to read/write to the location that is being saved to. We use this method in applications for delete/create folders across network. Even if App_Data is best practice, it may be a business requirement to access the documents outside of that folder.
You can also set impersonation on IIS.
I also notice that your function is called btnImportFile. You may want to look into FileUpload control if you are uploading a file, which allows you to get the byte array of the file and save as needed. https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.fileupload%28v=vs.110%29.aspx. You might still need to use Server.MapPath or HttpContext.Current.Request.ApplicationPath depending on your needs.
It's usually best practice to use the App_Data folder to save files to.
Take a look here, Working with files, for a tutorial.

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.

Get the file path of current application's config file

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.

Categories