Access to files on a server (asp.net, webmatrix) - asp.net

I want to read a *.txt file and edit this file. I use Webmatrix and it works on my computer. But after publishing it to a server (Web deploy) it doesn't work anymore.
string transmission;
string path;
path = "E:\\Documents\\My Web Sites\\Trackercontrol v2\\backup.txt";
public int insert()
{
using (StreamReader sr = File.OpenText(path))
{
while ((transmission = sr.ReadLine()) != null)
{
// etc.
}
}
}
I published this, adjusted the path to the .txt file, but the try/cath method told me that the access to the path is denied. I think reading out the file isnt the problem but editing or clearing the file makes this problem.
How can I fix this? Thank you very much!

You gave the path of your local drive, which may be or sure does not exist on the server. First upload the file on the server and then read it. You can get the correct path as
string path;
path = Server.MapPath("~/filename.txt"); // Considered file is placed at Root of your site

Check what account is the application pool running under?
Make sure that this account has read/write access to the file in concern.
Also, it would be a good idea to use
var path = Server.MapPath(relativePathToFile);

Related

What's the recommended way to load an internal file on the web site?

We've got a certain image in the \Images folder of our web site. We need to include that image in an OpenXml file we're generating internally, and for that we're using the following snippet:
var logo = Server.MapPath(#"~\Images\logo-new.png");
var imagePart = mainPart.AddImagePart(ImagePartType.Png); // mainPart is of type MainDocumentPart
using (var stream = new FileStream(logo, FileMode.Open))
{
imagePart.FeedData(stream);
}
Then later imagePart is used for embedding in the document.
This code works fine in development, but in deployment we're getting a System.UnauthorizedAccessException when we try to open the file for streaming.
Clearly there is an access permission problem, since Server.MapPath() is converting the web path to an absolute path on the server drive, and the IIS user doesn't have rights to that. We might be able to get around it by granting access to everyone, but something tells me that this is not the textbook way of doing it. Surely there must be a way of accessing this file that doesn't require us to start futzing with access permissions to the web deployment folder?
Solved, by including the file as a resource rather than by trying to access it through the file system:
var logo = Resources.logo_new;
var imagePart = mainPart.AddImagePart(ImagePartType.Png);
using (var stream = logo.ToStream(ImageFormat.Png))
{
imagePart.FeedData(stream);
}
Hat tip to this answer for the .ToStream() extension.

AjaxFileUpload file not inheriting folder permissions

I am successfully uploading a file using the AjaxFileUpload control from the AjaxToolkit. I had to give IUSR write permissions to the folder but after that there was no problem.
However, the files which are uploaded are not inheriting the permissions set on the folder, so they do not have IUSR listed. On my local machine this isn't much of a problem, but on the server it means a 401 is returned as IUSR read permission is needed on the file in order to read it.
From what I can see, the folder is set to apply permissions to files inside, which leads me to believe it is something to do with the way the file is saved to the folder. Does anyone know anything more about this?
UPDATE
OK so I found some more information about the problem. This article suggested that before the file is saved to the specified location, it is first held in a temporary location. The workaround they suggest (changing the temporary location to somewhere known and setting permissions on it) does not appear to work for the AjaxFileUpload. The rest of the project temporary files appear in there, but using the Process Monitor I can see that my temporary location is somewhere else entirely for the uploaded images:
If I set the permissions on this folder for IUSR then my problem is fixed. So the next question, will this location always exist? My guess is no. If so, how can I change it?
UPDATE 2
OK so I found there was some static methods on the control which are set to build the temporary directory:
public static string BuildTempFolder(string fileId)
{
return Path.Combine(AjaxFileUpload.BuildRootTempFolder(), fileId);
}
public static string BuildRootTempFolder()
{
string path = Path.Combine(Path.GetTempPath(), "_AjaxFileUpload");
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
return path;
}
One of the key lines is probably this: string path = Path.Combine(Path.GetTempPath(), "_AjaxFileUpload"); which seems to match with what I'd found in my process monitor. It seems that without rebuilding the project I'm stuck with their default settings, so I may look elsewhere for a different tool.
thanx chris
I had the same problem and I am not going to drop ajaxfileUpload control now , so I found workaround
1- download the source code from codeplex
2- open "source code directory"\Server\AjaxControlToolkit\AjaxFileUpload\AjaxFileUpload.cs and add static property name it UploadRootPath
public static string UploadRootPath
{
get;
set;
}
3- modify BuildRootTempFolder function :
public static string BuildRootTempFolder()
{
var rootTempFolder = "";
if (UploadRootPath == "")
{
rootTempFolder = Path.Combine(Path.GetTempPath(), TemporaryUploadFolderName);
}
else {
rootTempFolder = Path.Combine(UploadRootPath, TemporaryUploadFolderName);
}
if (!Directory.Exists(rootTempFolder))
Directory.CreateDirectory(rootTempFolder);
return rootTempFolder;
}
4- Build solution and use the new AjaxControlToolkit.dll in your project.
5- in your project set the directory where you want the temporary files to be saved in .
AjaxControlToolkit.AjaxFileUpload.UploadRootPath = Server.MapPath("~/Upload/Temp/");
I wish DevExpress guys do it in their next update , and I am sure they will do it in a decent way

download link give me filenotfound exception

in my controller, this is the code i have
public FileResult Download(string file)
{
var vFullFileName = HostingEnvironment.MapPath("~/App_Data/Files/");
var files = uploadedfileRepository.AllIncluding();
string filename = (from f in files
select f.FileName).First();
return File(Path.Combine(vFullFileName, filename), "application/csv", filename);
}
I put the breakpoint and the file point to the right directory, but why still give me File not found exception?
and in my view this is what i have
<td>
#Html.ActionLink("Download", "Download", new { id = item.FileName})
</td
Your action method have a parameter with name file. But your are HTML will have a parameter/ query string called id, instead od file, So change your view code to
#Html.ActionLink("Download", "Download", new { file= item.FileName})
Also to get the path, try this
string fullFilePath=Path.Combine(Server.MapPath("~/App_Data"),filename)
return File(fullFilePath,"application/csv",filename);
App_Data is for database files that are accessed by MS SQL Server, and possibly your application's own data files (like a Lucene index).
IIS (and ASP.NET) are configured to block any client requests to that directory.
The solution is just to move the files to another directory. Just create a new folder in your site's root (say "CsvFiles") and link to that.
That said, why don't you serve up a HTTP 301 Redirection (or even a direct link) to the CSV files instead of serving them via your application?
UPDATE: This answer is incorrect because by serving the file contents via an MVC File response the user's browser doesn't acutally access the App_Data directory.

Download and run file in client machine using asp.net

I'm trying to download and run a file to the client machine. The client is aware of that.
It's a ttkgp file that's dynamicly generated.
I've tried using Processs.Start() that worked fine on my local machine (first saved the file to C:\ then lunched it), but it's not working from the server. It's not my server but a hosted one. They are trying to help but no luck so far.
I've seen this code:
public void ProcessRequest(HttpContext context)
{
string fileName = context.Request.QueryString["filename"];
FileInfo fi = new FileInfo(fileName);
context.Response.ContentType = "application/x-rar-compressed";
context.Response.AppendHeader("Content-Disposition",
string.Format("attachment; filename=download{0}", fi.Name));
context.Response.WriteFile(fileName);
context.Response.End();
}
But since I dont know what's "HttpContext context" is, I've no idea if it works.
Is it some server previlges need to be changed? or simply this code will do the trick?
Thank you
UPDATE (24.6.12): I'm nearly finished with the problem, all I need now is to know how to open an html page in a new tab / window and close it second later. Once I'm done, I'll post back here all the process, I'm sure it'll help other people.
UPDATE (26.6.12):
Here's what I've got:
The goal is to download an TTKGP file from asp.net webiste to local user machine and run it.
Step 1: generate the file with code behaind (c#) on the server (V)
Step 2: copy the file or it's content to user machine (X)
Step 3: run the file using JS (V)
Here's the thing: I CAN copy from a text file on the server to a text file on the user machine, but not from TTKGP files. It's strange because this are just text files just a different extantion.
The code for copying text files:
enter code here
function copyremotetxt() // works
{
// copy the txt file
var fso = new ActiveXObject("Scripting.FileSystemObject");
var newfile = fso.CopyFile("remote.txt", "C:\\Users\\***\\local.txt");
}
Perhaps I can change the file type on the user machine?
Notice 1: I know that's a security issue, the site is just for known user not the open public
Notice 2: I know there are better ways to get the task done, but there are strict limitaions on many things
Thanks for those how can help!!
This code will do the trick. It will prompt the client to download and save the file on his computer at the location he decides. What happens next with this file is the client's decision, not yours. He might simply close the Save As dialog, interrupt the download, delete the file, ... It's up to him.
Another remark: this code is extremely dangerous because it allows the client to pass any filename he wants as query string parameter and download it. So he could read absolutely all files on the server which is probably not something that you want to happen.
Ok, this need a different aproach.
I'll try using JavaScript do read the file on the server, rewrite it in the user machine and activate it. Any clues would be grate! For a start, how to I read file in JS? I'm new to it.

asp.net File.OpenText can't read uploaded file

I have an ASP.NET MVC application on Windows Server 2008.
I need to upload a file, save it to an archive folder under the App_Data folder, then open and read from it. I can do this on my local machine but can't on the test server. I suspect it is a permissions issue but the permissions appear to be in place. The relevant C# code:
HttpPostedFileBase hpf = Request.Files[0];
var fileLength = hpf.ContentLength;
if (fileLength != 0)
{
var archiveFolder = Server.MapPath("~/" + folder);
var archiveFile = "import_" + DateTime.Now.ToString("yyyyMMdd_HHmm") + ".txt";
var archivePath = Path.Combine(archiveFolder, archiveFile);
hpf.SaveAs(archivePath);
}
The above code saves the file fine.
StreamReader sr = File.OpenText(archivePath);
The above line throws an error:
Could not find file 'c:\windows\system32\inetsrv\usb01312012.txt'.
So although "archivePath" is a path to a saved file under App_Data, ASP.NET looks to the SYSTEM folder for the file.
I have given every permission except Full Control to IIS_USRS on the entire website. Why can't I access the file?
Make sure your site runs correct version of asp.net (2.0 or 4.0).
RESOLVED: As of the next day, this now works! I guess IIS had to recycle? Thanks for your comments!

Resources