asp.net MVC3 create folder where application can write in - c#

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.

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.

Can i use clickOnce to deploy MS Access database?

i have developed an application in a .mdb access file with tables linked to sql server
i try toput the mdb file in folder shared to all user but simultaneus access break the file very often.
so iam trying to deploy the .mdb file to every client machine and keep it update. i have created a winform app that check mdb file version and copy it to a local folder and next opens the local copy
but even in this way i have problem if too many user uses the winform launcher appat same time
so iam thinking if there is a bettere and simpler way:
can i use clickonce to deploy directly the access file and create a silly webform to launch it?
i have created the webform but how can i add the mdb file to deploy process? i have to add it to resources? and in that case embedded or not?
and in that case how clickonce detect that the access is a modified one?
If I understand correctly, your .mdb file is the front end to a SQL Server back end. In that case, yes, each user should have their own copy of that FE. If you do a web search, there are many solutions for distributing an Access FE, without having to re-invent the wheel. A favorite is Tony's Auto FE Updater http://autofeupdater.com/.
Found the solution finally:
i add the db to Resources, setting build action to "Content", then my program.cs is this:
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
string nomeFile = #"\EW.accde";
string DestinationPath;
string codeBase = Assembly.GetExecutingAssembly().CodeBase;
UriBuilder uri = new UriBuilder(codeBase);
string path = Uri.UnescapeDataString(uri.Path);
DestinationPath = System.IO.Path.GetDirectoryName(path) + #"\Resources";
Process.Start(DestinationPath + nomeFile);
}
in this way i simply copy the new db in project and then deply app with clickonce
once installed app simply launch the database file

To browse folder and Create folder in the server and upload files using asp.net

I am Currently working on asp.net i have worked on file upload by uploading files but i want browse a folder not a file and get all files in it and get foldername and create foldername in server and upload files it to server.Pls give me some refernce and help me to do this.
My aim is when i browse that folder all it files present in it should upload .Only files should upload not folder
Note:To browse folder not file.
Actually you are supposed to include a question if you want an answer, but it seems you are completely new to this so here are a few things you should know when it comes to asp.net and folder/file handling:
Your virtual path always corresponds to a local path on your webserver. Since it would be bad to hardcode that you might want to start off by mapping it. (e.g. /uploads/ to _C:\intepub\application\uploads)
"and get foldername"
string localpath = Server.MapPath("/uploads");
"and create foldername in server"
next you can check if that folder already exists, or if not - create it.
if(!System.IO.Directory.Exists(localpath))
System.IO.Directory.Create(localpath))
Keep in Mind though that your IIS-User needs the rights to create new directories
Now that you have made sure that your upload directory exists, you can upload/download files. Here is a good tutorial to get started:
"and upload files it to server"
http://msdn.microsoft.com/en-us/library/aa479405.aspx
"but i want browse a folder not a file and get all files in"
You can do that on the server, not the client. Your asp.net code never executes on the client.
string[] filenames = System.IO.Directory.GetFiles(localpath);
"My aim is when i browse that folder all it files present in it should upload"
That one isn't so easy, sorry. It would pose a serious security risk to users.
Maybe this will point you in the right direction (apparently it works with Chrome)
How do I use Google Chrome 11's Upload Folder feature in my own code?
When it comes to files, directories, filepaths, etc. in general, I would recommend taking a closer look at these classes:
System.IO.File
System.IO.Directory
System.IO.Path

ERROR: System.Environment.SpecialFolder' does not contain a definition for 'CommonApplicationData'

I have the code to save a file in a folder in directory
string timestamp = DateTime.Now.ToString("MM-dd-yyyy.HH-mm-ss");
var file = File.Create("Owe-Data.txt" + timestamp);
var com = System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase + timestamp + #"\Data" + file;
MessageBox.Show(com);
if (!Directory.Exists(com))
{
Directory.CreateDirectory(com);
}
using (var sw = new StreamWriter(com))
{
sw.WriteLine(InputData);
}
}
i Displayed COM it gives path bt i cant see the Data folder or Owe-Data file at that path
Anybody can tell why this happening, or should i save the Data folder in current directory where this prgram running? bt i dnt know how to reach that path. Any solutions ??
Working on windows phone 5, visual studio 2008 .NET framwork 2.0
As per the Exceptions section of documentation,the above exception is thrown when
ArgumentException ------- folder is not a member of System.Environment.SpecialFolder.
It means the OS where you are running this command does not have Environment.SpecialFolder.CommonApplicationData as one of the special folder.
For knowledge,
Environment.SpecialFolder.ApplicationData is the most common one. This folder holds per-user, non-temporary application-specific data, other than user documents. A common example would be a settings or configuration file.
Environment.SpecialFolder.CommonApplicationData is similar, but shared across users. You could use this to store document templates, for instance.
Environment.SpecialFolder.LocalApplicationData is a non-roaming alternative for ApplicationData. As such, you'd never store important data there. However, because it's non-roaming it is a good location for temporary files, caches, etcetera. It's typically on a local disk.
I think the problem may be that Environment.SpecialFolder.CommonApplicationData is common and shared between different users and the user with which you have logged in is not having rights to access the folder or the Visual Studio has not been started in Admin mode.
EDIT Look at link and try to add a manual registry Common AppData defined in the HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders\
Given you are asking about a .NET Windows Phone application as per the tags
I think your problem is that a .NET Windows Phone application does not have direct access to the file system; it can only access IsolatedStorage this is by design.
I would quote a Microsoft source for this but I can't seem to find one!
EDIT
See this article from MSDN

Can't access server file

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.

Categories