Can't access server file - c#

I am trying to access server files, one for reading and other for writing. The following is the path I am setting to achieve this:
var templatePath = Server.MapPath(#"~/Templates/SRG_Template.pptx");
var outputPath = Server.MapPath(#"~/Output/SRG_Document.pptx");
However, I am not able to access them.
Update: In Template folder lies the PowerPoint template which I am reading to create PowerPoint file in Output folder. When I run the application locally, it works fine but on running on server, the ppt file is not created.

I think that your problem is IIS Security Permission.
Did you try that?
You must grant access to IIS_IUSRS user for read, write and modify files on Template and Output folders.
You can read more about this Here.

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.

How do I upload a resource file and then access that file in an Azure Cloud Service?

I want to have my Worker Role (have not done this with a web role) upload a file when it is deployed and also be able to access that deployed file in code.
How do I deploy a file with my Cloud Service to each instance?
How can I find that file in code?
Good question, Adam. To deploy a file with your cloud service you can follow this article. The 2 main points are as follows:
set Build Action to None
set Copy to Output Directory to "Copy if newer"
With these two properties set the file and its folder structure will be copied to your instance deployment. Things brings us to accessing that file in code.
To access it in code simply do the following which I got from here:
string appRoot = Environment.GetEnvironmentVariable("RoleRoot");
string pathToFiles = Path.Combine(appRoot + #"\", #"approot\" + "anyFolderNameIUsed\");
It is important to remember that this is part of the deployment package which means this file will be overwritten whenever the deployment is completed again. Also, each instance will have it's own version of the file.
If you need persistance or the ability to share file contents between your worker roles you can save your files in Blob Storage. The following article can you help accomplish this.
Using Blobs

Download File via Tamir.SharpSSH.Sftp.Get()

I'm trying to download a file using the Tamir SSH library. I'm able to connect to the remote FTP site, upload files to the site, but I'm getting exceptions when trying to download. I've given IIS_IUSRS full control of the local directory as well as ASPNET. I've tested an I'm able to create a text file in the same local directory I'm trying to download to. Any ideas?
string SFTP_HOST = ConfigurationManager.AppSettings["AccentivFtpHost"];
string SFTP_USERNAME = ConfigurationManager.AppSettings["AccentivFtpUsername"];
string SFTP_PASSWORD = ConfigurationManager.AppSettings["AccentivFtpPassword"];
Sftp client = new Sftp(SFTP_HOST, SFTP_USERNAME, SFTP_PASSWORD);
client.Connect(22);
client.Get("test.txt", "c:\\test.txt");
You probably lack a '/' character in the file directory. You may need to put it either in the Get function call before the "test.txt" like "/test.txt" or at the end of your AccentivFtpHost value in the app config file.

asp.net MVC3 create folder where application can write in

I need to create a folder to use for storing files within it, in a .Net MVC3 application, but I think the problem is common to all ASP.Net platform.
Problem is I can create the folder, but cannot write the files, because System.UnauthorizedAccessException occurred.
I also tryed givin extra permission to the user currently running the web app, but nothing changes.
This is my code so far:
if (!System.IO.Directory.Exists(fullPath))
{
System.IO.Directory.CreateDirectory(fullPath);
var user = System.Security.Principal.WindowsIdentity.GetCurrent().User;
var userName = user.Translate(typeof(System.Security.Principal.NTAccount));
var dirInfo = new System.IO.DirectoryInfo(fullPath);
var sec = dirInfo.GetAccessControl();
sec.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule(userName,
System.Security.AccessControl.FileSystemRights.Modify,
System.Security.AccessControl.AccessControlType.Allow)
);
dirInfo.SetAccessControl(sec);
System.IO.Directory.CreateDirectory(fullPath);
}
string fullPathFileName = System.IO.Path.Combine(fullPath, fileName);
System.IO.File.WriteAllBytes(fullPath, viaggio.Depliant.RawFile);
Too bad, last line of code always throw System.UnauthorizedAccessException.
I'm not impersonating user in my app, everything run under a predefined user.
What should I do to create a folder and assure that the application can also create files within it?
Edited:
I also tryed to save the files in the App_Data special folder, but I still got the System.UnauthorizedAccessException error. Somebody can tell me why is that happening?
I hate to answer my own question when the problem is that stupid...
I'm just trying to save a file without a proper filename: you can see I'm using the fullPath variable both for creating the folder and for saving the file, instead of using the correctly created fullPathFileName.
Blame on me!
Use App_Data folder, quote from http://msdn.microsoft.com/en-us/library/06t2w7da%28v=vs.80%29.aspx :
To improve the security of the data used by your ASP.NET application, a new subfolder named App_Data has been added for ASP.NET applications. Files stored in the App_Data folder are not returned in response to direct HTTP requests, which makes the App_Data folder the recommended location for data stored with your application, including .mdf (SQL Server Express Edition), .mdb (Microsoft Access), or XML files. Note that when using the App_Data folder to store your application data, the identity of your application has read and write permissions to the App_Data folder.

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

Categories