ShellClass.BrowseForFolder(...) DialogBox not showing - c#

I have a .aspx page in my project inside that there is one <a> link for download .txt files.
Am using Shell32.ShellClass and Shell32.Folder2 for showing Browse For Folder for ask user to Where do you want to save files instead it download on default Downloads folder.
Below is my C# code for showing DialogBox.
Shell32.ShellClass shell = new Shell32.ShellClass();
Shell32.Folder2 flder = (Shell32.Folder2)shell.BrowseForFolder(0, "Select destination folder", 0,"Desktop");
if (flder == null)
{
dlgResult = DialogResult.Cancel;
}
else
{
strPath = flder.Self.Path;
dlgResult = DialogResult.OK;
File.WriteAllText(strPath + "\\NewFile.txt", "file content abc tex...");
}
Problem: Above code working fine in Local but when I host website on IIS it's not working and not showing DialogBox.
Is there any specific Settings or Configurations in IIS for that ? or why it's not working when it host in IIS?
please give me suggestions.
Thanks.

Your C# code runs on the server, not in the web page. When you open a dialog box in this way, it runs in the context of the calling code. When running as part of IIS express (or any web server running as you), it opens in your Windows desktop because it is running as you. When running in IIS, it is running as a different account not attached to your desktop, so it will not show.
I am not aware of a way to invoke the "Save As" functionality to save a file to a different folder in JavaScript. The execCommand function may work but it varies from browser to browser. Some versions of Internet Explorer also limit what file types can be downloaded this way.

Related

Application can find 'Downloads' folder when debugging but not on IIS

I have an application that allows the user to upload a file (saving it to in a folder located in the wwwroot of the ASPNETCORE application). From here they can make edits to it and then they can choose to export the file as a csv/ xml/ xlsx which downloads the file to the user's 'downloads' folder.
While debugging in Visual Studio this all works fine however when I publish and deploy the application to IIS I am getting the exception
Error saving file C:\windows\system32\config\systemprofile\Downloads(FILE NAME)
Could not find part of the path C:\windows\system32\config\systemprofile\Downloads(FILE NAME)
This is the current way I am getting the downloads folder:
FileInfo file = new FileInfo(Path.Combine(Environment.ExpandEnvironmentVariables(#"%USERPROFILE%\Downloads"), data.Filename + "." + data.FileType));
However I have also tried the solution that Hans Passant has answered to a similar question here. Both solutions worjk fine while debugging locally however as soon as I publish them, this one produces the exception:
Value cannot be null. Parameter name: path1
Which I presume is thrown at this point here when I try and save the file to the user's download folder.
using (var package = new ExcelPackage(file))
{
var workSheet = package.Workbook.Worksheets.Add("ExportSheet");
workSheet.Cells.LoadFromCollection(exports, true);
package.Save();
}
I don't really know how I would be able to reproduce these exceptions seeing as locally using Visual Studio it all works fine.
Has anyone else came across this issue while trying to download a file?
UPDATE: When the application is running on IIS, it seems to be using that as the user profile instead of the actually user, so when it tries to navigate to the Downloads folder, it cannot find it. How can I force it to use the user's profile?
LoadUserProfile is already set to True.
Web applications have no knowledge of the end-user's computer's filesystem!
So using Environment.GetFolderPath or Environment.ExpandEnvironmentVariables in server side code will only reveal the server-side user (i.e. the Windows Service Identity)'s profile directories which is completely separate and distinct from your web-application's actual browser-based users OS user profile.
As a simple thought-experiment: consider a user running a weird alien web-browser on an even more alien operating system (say, iBrowse for the Amiga!) - the concept of a Windows-shell "Downloads" directory just doesn't exist, and yet here they are, browsing your website. What do you expect your code would do in this situation?
To "download" a file to a user, your server-side web-application should serve the raw bytes of the generated file (e.g. using HttpResponse.TransmitFile) with the Content-Disposition: header to provide a hint to the user's browser that they should save the file rather than try to open it in the browser.

SEC7134: Resource '...' not allowed to load. SCRIPT70: Permission denied

When using the below code to try to open File Explorer to a folder path I get the errors SEC7134: Resource 'file://...' not allowed to load, and SCRIPT70: Permission denied.
However if I copy the exact path returned in the error and past it into the url it opens a new file explorer window without any issues. This was working at one time for me as expected, I'm wondering if there have been security changes or things that need to be updated on my side to open these files in File Explorer again.
Thanks,
function openFile(path) {
// Internet Explorer 6-11
var isIE = /*#cc_on!#*/false || !!document.documentMode;
// Edge 20+
var isEdge = !isIE && !!window.StyleMedia;
if (isIE || isEdge) {
window.location.href = path;
return false;
}
}
Yes, we could use the browser as file explorer to retrieve the files in our local environment. But, reading local files from the browser (using JavaScript) is not allowed. This will prevent websites reading files and stealing your information.
If you want to display the local file using JavaScript, you could use the upload control select the local file, then, read the file and display it.

Run process.start() in a network

I have written a win application that works on a network.
In one of its forms user can browse and select file from local computer and add it to a list, so the application copies these files to a folder in My Network Places that no users can access to it but one that i have created already for my application so i have his username and password.Every things works fine up to here.
In this form user can also open a file by select it and press open button, so the file should open in an application that relates to its extension(for example test.xlsx should open in Exel.exe).I have used Process.Start() to do this but for each extension i receive an individual error(for example "Access is denied" for NotePad and "RunTime error" for AdobeReader and "Not enough memory" for Excel).
What is my mistake?
Note : I have used ImpersonatUser to logon that user in my application.
Edit : I have used following code to open the file :
Using(WindowsImpersonationContext impersonateUser = LogonMethod())
{
ProcessStartInfo pInfo = new ProcessStartInfo(filePathWithExtension);
pInfo.Domain = MyDomainName;
pInfo.UseShellExecute = false;
Process.Start(pInfo);
}
Note : My LogonMethod uses LogonUser method of advapi32.dll.
The behavior you are seeing is almost expected.
it looks like you are not launching application directly, but rater using association by file name. I don't believe you'll get application launched under account you want. You can check what account application is run unrder using task manager.
Most application are not tested to run in "run as" context, so they may work correctly or fail randomly.
I could not solve this problem, so i have used another way.I have copied the file to a temp folder and then used Process.Start to open this new file.

Can't create a file in C:\inetpub\wwwroot programmatically

I have a function in the code behind of an ASP.NET webpage that creates a file and then opens it with a javascript command. This works in the IDE - it creates the file, asks me where I want to save the file, I can save it, etc. - but when I install the website and test it out, I get an UnauthorizedAccessException while just trying to create the directory for the file within C:\inetpub\wwwroot.
The frustrating part is that I have a similar function that runs in a service and that creates its directories and files just fine in C:\inetpub\wwwroot.
What would I have to do to get this to work for a webpage?
if(!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
StreamWriter SW = new StreamWriter(fullpath, false, Encoding.Unicode);
SW.WriteLine(/*stuff*/);
SW.Close();
You need to make sure the .NET user has write access by right-clicking on the directory, going to the security tab, and adding the appropriate user and checking the write checkbox.
Depending on your version of .NET/Windows/IIS this can be different, typically it is Network Service or IUSR. If you are running IIS7 make sure to check the Identity under advanced settings of the application pool, as that will be the user that needs the write access, again typically this is Network Service.
You need to grant the ASP.Net user write access to the directory.
just open your text editor( notepad or textpad or anything) using administrative previledges
right click on .exe file and click run as administrator you will be able to do it now

Download and save aspx page

I saved aspx page as html it worked in my local machine but after published on the server its showing an error that "the access to the path is denied"... I tried giving access permission then also it doesn't work.. can anyone help with it? or else is there any other way to save the page in C# asp.net?...
string url=HttpContext.Current.Request.Url.AbsoluteUri;
string sHtml="";
HttpWebRequest request;
HttpWebResponse response=null;
Stream stream=null;
request=HttpWebRequest)WebRequest.Create(url);
response=(HttpWebResponse)request.GetResponse();
stream=response.GetResponseStream();
StreamReader sr=new StreamReader(stream,System.Text.Encoding.Default);
sHtml=sr.ReadToEnd();
string path=Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string textfilename=TextBox1.Text;
string getpath=path+"\\"+textfilename+".html";
File.WriteAllText(getpath,sHtml);
if(stream!=null)stream.Close();
if(response!=null)response.Close();
Thanks..
If you need to save a file use this to get the application path
Server.MapPath(#"filename.txt");
Try this because when you only write the filename at an web server you are trying to access to a Microsoft.Net folder.
yes make sure the folder you write to has the appropriate privileges. IIS 5 uses ASPNET account, IIS6 uses network service. Just give read/write to the proper account. Is this your dev environment, or a prod environment?
Also, make sure it's pointing to a folder; desktop folder for ASPNET account probably won't exist since ASPNET account isn't a user with a users folder.
I had a similar problem when trying to deploy CSS from a ZIP downloaded from the web. Try right-clicking on the aspx file from windows explorer and checking the file properties. One of the tabs may indicate that the file has been "blocked". If so, there will be a button there to unblock it.

Categories