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

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!

Related

Dynamically created css not working on Azure website

I am working on Web Form project to deploy on production. In this project, dynamic folder is created on fly and put the new css style as per data configuration from database. This was handled by Handlers in web form. Application works locally without any error. But when I publish on production it does not find the dynamic created css file path. Its not physical exists it creates on fly. So it fails to download css and it missing all images and styles. Another team had developed this application and we are moving this from FireHost to Azure site. It was working on Firehost but no any luck on Azure site yet. I tried to remove manifest file in production by adding remove attributes .manifest in web.config. But no any luck yet. I appreciate your help Thanks
I am getting 404 errors,
Failed to load resource: the server responded with a status of 404 (Not Found)
I have the style css inject this way in site.master page.
<link href="/Styles/Dynamic/CompanySite.css" rel="stylesheet" type="text/css" />
It did not mentioned handlers in web.config. There is separate handlers folders and pages. In pages code behind file look like this in page load method.
StringBuilder sb = new StringBuilder(File.ReadAllText(Server.MapPath("~/Styles/CompanyStyles.css")));
string sPrimaryColor = "#B1D74C";
string sSecondaryColor = "#8BBB29";
string sPrimaryTextColor = "#000";
string sSecondaryTextColor = "#000";
string sBannerId = "1";
try
{
var settings = new CompanySettingDataLogic().Retrieve();
if (settings != null)
{
sPrimaryColor = settings.primary_color_txt;
sSecondaryColor = settings.secondary_color_txt;
sPrimaryTextColor = settings.primary_text_color_txt;
sSecondaryTextColor = settings.secondary_text_color_txt;
}
var BannerId = new CompanyThemeDataLogic().GetBannerId();
if (BannerId.HasValue)
sBannerId = BannerId.Value.ToString();
}
catch (Exception Ex)
{
new Data.Config.ErrorLogDataLogic().LogException(Ex);
}
sb.Replace("#PRIMARY#", sPrimaryColor);
sb.Replace("#SECONDARY#", sSecondaryColor);
sb.Replace("#PRIMARYTEXTCOLOR#", sPrimaryTextColor);
sb.Replace("#SECONDARYTEXTCOLOR#", sSecondaryTextColor);
sb.Replace("#BANNERIMAGEID#", sBannerId);
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.Cache.SetCacheability(HttpCacheability.Private);
Response.Cache.SetExpires(DateTime.Now.AddDays(2));
Response.ContentType = "text/css";
Response.Write(sb.ToString());
Its not physical exists it creates on fly. So it fails to download css
and it missing all images and styles.
Where have you stored the files after the folder being created? Do you store them in website Azure vm disk? Please note
the VM disk storage is not persistent
if you have >= 2 instances on Azure to host the web app, and then you just created the css/images files on 1 instance (VM), later your end user may hit the other instance that has no such files.
so please store your files in Azure storage - blob and use its url in your project to connect to css/image files

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

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

Programmatically retrieving IIS log file location in an ASP.NET application

I'm trying to determine the location of the IIS log file location of my ASP.NET application. I tried WMI, but wasn't able to find it. Any suggestions?
Note: I want to be able to retrieve the location programmatically; inside my application for further use.
Edit: Here's my code: This works but does not give me the actual physical directory location of the logs. So this is basically useless.
ManagementPath p2=new ManagementPath("IIsLogModule.Name='logging/Microsoft IIS Log File Format'");
ManagementObject log = new ManagementObject(scope, p2, objectGet);
log.Get();
logPath.Text = log["__PATH"].ToString();
On IIS7 you could use Microsoft.Web.Administration assembly, Site class has a property named LogFile, you can get various info about log file for site, for example log file directory can be obtained with this code:
ServerManager manager = new ServerManager();
Site mySite = manager.Sites["SiteName"];
Response.Write("Log file directory : " + mySite.LogFile.Directory + "\\W3svc" + mySite.Id.ToString());
I don't like very much that hardcoded part with directory prefix for site, but didn't find any other better way
You should able to use ADSI (or WMI) to do that - browse IIS metabase and look for 'LogFileDirectory' property for the web site node. For example,
var root = new DirectoryEntry(#"IIS://localhost/W3SVC");
var sites = root.Children;
foreach(DirectoryEntry site in sites) {
var name = site.Properties["ServerComment"][0];
var logFile = site.Properties["LogFileDirectory"][0];
}
Disclaimer: Untested code
See this powershell example using similar idea.

asp.net File.Copy Lock

I have an Asp.net page which allows file uploads and then copies the newly uploaded file to another folder. So far so good. Problem is that the copied file is used in the other folder for some other needs (e.g. using FileStream to open the copied file). But asp.net puts a lock on the copied file. I can't even open the copied file using Windows Explorer so long as the Visual Studio's builtin web server is running. I get an error like:
The process cannot access the file 'C:\inetpub\wwwroot.....pdf' because it is being used by another process
Here is partial code:
System.IO.File.Copy(targetFolder_live + "\\" + finalfilename, targetFolder_encr + "\\" + finalfilename);
createpreviewdoc(finalfilename);
////inside the createpreviewdoc function
FileStream stream = new FileStream(targetFolder_encr + "/" + file, FileMode.OpenOrCreate);//Fails with the error!
So what can be done to remove the lock in the same page load? Thanks!
I would attempt the copy in a different fashion.
FileInfo fileInfo = new FileInfo("PathToOriginal");
fileInfo.CopyTo("MyNewLocation");
File.OpenText("MyNewLocation"); // works for me

Downloading bin folder's dll file of ASP.Net App

I just want to know , Is this possible to download my application's dll file from production server's bin directory...
Not via HTTP, if that's what you mean. You don't generally want to make that file available in that way.
If for some reason you want to make it available, like in some kind of code sharing scenario, I would code up a page that streams it out directly:
var fullQualifiedPathToDll = Server.MapPath("/") + "/bin/mydll.dll";
var myFileStream = new FileStream(fullQualifiedPathToDll, FileMode.Open);
var fileSize = myFileStream.Length;
var buffer = new byte[(int)FileSize];
myFileStream.Read(buffer, 0, (int)FileSize);
myFileStream.Close();
Response.BinaryWrite(buffer);
Be VERY sure that this is what you want to do when you're doing it. This is adapted from a sample found here.
Under normal circumstances, no. ASP.NET blocks requests to the bin directory.

Resources