System.IO.FileNotFoundException Cannot find file - asp.net

I am using google as an smtp client to send an email and am having troubles with sending the attachment, i am using an asp:fileupload to choose the file then using the fileupload.filename to select the attachment. Here is the Error message.
System.IO.FileNotFoundException: Could not find file 'C:\Program Files (x86)\IIS Express\ISO Certificate.pdf'. File name: 'C:\Program Files (x86)\IIS Express\ISO Certificate.pdf' at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost) at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share) at System.Net.Mail.AttachmentBase.SetContentFromFile(String fileName, String mediaType) at System.Net.Mail.AttachmentBase..ctor(String fileName) at System.Net.Mail.Attachment..ctor(String fileName) at frmQuote.btnSubmit_Click(Object sender, EventArgs e) in c:\Users\jack\Documents\Visual Studio 2013\WebSites\firstarPrecision\frmQuote.aspx.cs:line 46
Then here is the C# Code to go along with it
try
{
SmtpClient client = new SmtpClient("smtp.gmail.com", 587)
{
Credentials = new NetworkCredential("EMAIL", "PASSWORD"),
EnableSsl = true
};
var msgQuote = new MailMessage
{
Subject = strQuoteSubject,
Body = strQuoteBody,
From = new MailAddress("EMAIL"),
};
//HINT HINT HERE IS WHERE THE ERROR OCCURS, I JUST DONT KNOW WHY :(
//HOW DO I TURN OFF CAPS LOCK
Attachment att = new Attachment(fupAttachment.FileName.ToString());
msgQuote.Attachments.Add(att);
msgQuote.To.Add(new MailAddress(strEmail));
client.Send(msgQuote);
}
catch (Exception ex)
{
Response.Write(ex);
}
there is the code, i obviously blocked out my credentials and such... at least i hope i got all of it.

An uploaded file needs to be saved to the server, or you could pass the file stream to the attachment (if the API supports it, not 100% sure). Either way, what you are giving it is insufficient. Save the file stream on the fupAttachment object, and then attach the file from that location. Also, depending on the version of IIS you are using determines which account accesses the file stream for permissions. The latest IIS uses an account for the apppool that needs the permissions.

Related

XMLSerializer throws Access Denied exception when code runs on web server but not locally

When I run the following line of code locally it runs succesfully. When I upload the code to the Arvixe web server I get the exception. I can read and write the temp folder as found by Path.GetTempPath()
I understand that XMLSerializer needs a temp path to create .DLLs. Does ASP.NET use a different temp path that it does not have permissions? I have compiled as Generate Serialization Assemblies Auto, Off and On to no avail. It must be a server setting as it runs on another Arvixe server but I dont know what to ask the server admins to do.
'This is the code line that causes the exception:
Sub Test
Dim formatter = New XmlSerializer(GetType(TestSMTPClass))
End Sub`
'This is a simple class we are trying to serialize
Public Class TestSMTPClass
Property ServerIP As String
Property Port As String
End Class
Throws this exception
Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
ex.ToString
System.UnauthorizedAccessException: Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
at System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo)
at Microsoft.Win32.Fusion.ReadCache(ArrayList alAssems, String name, UInt32 nFlag)
at System.Reflection.RuntimeAssembly.EnumerateCache(AssemblyName partialName)
at System.Reflection.RuntimeAssembly.LoadWithPartialNameInternal(AssemblyName an, Evidence securityEvidence, StackCrawlMark& stackMark)
at System.Reflection.Assembly.LoadWithPartialName(String partialName, Evidence securityEvidence)
at System.Xml.Serialization.TempAssembly.LoadGeneratedAssembly(Type type, String defaultNamespace, XmlSerializerImplementation& contract)
at System.Xml.Serialization.XmlSerializer..ctor(Type type, String defaultNamespace)
at OCC_Competition.TestSMTP.btnTestCode_Click(Object sender, EventArgs e)

System.IO.IOException: operation did not complete successfully because the file contains a virus

I am using below code, sometimes I face the exception
System.IO.IOException: operation did not complete successfully because the file contains a virus
string name = Request.Form["__VIEWSTATE_KEY"];
object state = null;
string fileName = string.Format("{0}\\{1}.dat", Environment.GetEnvironmentVariable("TEMP"), name );
StreamReader reader = null;
try
{
reader = new StreamReader(fileName);
state = (new LosFormatter()).Deserialize(reader);
}
catch (FileNotFoundException)
{
state = null;
}
Exception Detail:
System.IO.IOException: Operation did not complete successfully because the file contains a virus or potentially unwanted software.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
at System.IO.StreamReader..ctor(String path, Encoding encoding, Boolean detectEncodingFromByteOrderMarks, Int32 bufferSize, Boolean checkHost)
at System.IO.StreamReader..ctor(String path, Encoding encoding, Boolean detectEncodingFromByteOrderMarks, Int32 bufferSize)
at System.IO.StreamReader..ctor(String path, Boolean detectEncodingFromByteOrderMarks)
at PageBase.LoadPageStateFromPersistenceMedium()
at System.Web.UI.Page.LoadAllState()
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
I don't think Defender is to blame. Unsafe is unsafe. Defender may have been set to guard against the use of this deserializer. Microsoft has labeled LosFormatter as unsafe in 2019, because it allows too much freedom in the type specified,
https://learn.microsoft.com/en-us/visualstudio/code-quality/ca2305?view=vs-2019
Windows Defender Advanced Threat Protection can cause .NET file operations to fail with this exception. This might not be false positive, so first scan your system, but then you can exclude your build directory.
Excluding Build directories can also speed up your build times considerably, but be aware of the risk and make sure you trust the code you're building.

Access to path denied when i write and save the file on server

System.UnauthorizedAccessException: Access to the path 'C:\Inetpub\wwwroot\HealthCard\NewsTextFiles\News.html' is denied.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access)
I am using ckeditor . Edit the file on server and save the file on server. It is not working on server but it is well working on my localmachine.
Here is code of edit and save button.
protected void btnSaveNews_Click(object sender, EventArgs e)
{
string str = Ckeditor.Text;
string str1 = Server.HtmlDecode(str);
//lblText.Text = str2;
FileStream fs = new FileStream(Server.MapPath("~/NewsTextFiles/News.html"), FileMode.Create , FileAccess.Write);
StreamWriter wr = new StreamWriter(fs);
wr.Write(str1);
wr.Dispose();
fs.Dispose();
pnleditor.Visible = false;
upleditor.Update();
upleditor.Visible = false;
}
Make sure the user your Application Pool is running as has write permissions on that file / folder.
This might be:
IIS_USR or Network Service (can also be others).

Grant ASP.NET MVC 3 website write access to ~/Content/uploads folder

I have an ASP.NET MVC 3 website that runs on the company intranet to which I want to add a page that can upload files to the server.
I am running the site on Windows Server 2012 with IIS 8.
IIS Config:
Application pool attributes:
.Net Framework v4.0
Managed Pipeline Mode: Integrated
Identity: LocalSystem
Under the site node, authentication is set as:
Windows Authentication: Enabled (Users must use their corporate Windows Accounts to log in)
All other Authentication including Anonymous Authentication set to Disabled.
Windows Permissions:
In the Content directory, I have granted all access permissions to the System, Admin and my User's account.
MVC Code:
The MVC Controller method that handles the file upload contains the following code:
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
if (file != null && file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
DateTime timestamp = DateTime.Today;
var path = Path.Combine(Server.MapPath("~/Content/uploads"), fileName);
if( !Directory.Exists(path))
Directory.CreateDirectory(path);
file.SaveAs(path);
}
return RedirectToAction("Index");
}
When I try to upload a file using the above controller I get the following error:
Server Error in '/' Application.
Access to the path 'C:\Sites\ClosedBeta\Content\uploads\test.csv' is denied.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.UnauthorizedAccessException: Access to the path 'C:\Sites\ClosedBeta\Content\uploads\test.csv' is denied.
ASP.NET is not authorized to access the requested resource. Consider granting access rights to the resource to the ASP.NET request identity. ASP.NET has a base process identity (typically {MACHINE}\ASPNET on IIS 5 or Network Service on IIS 6 and IIS 7, and the configured application pool identity on IIS 7.5) that is used if the application is not impersonating. If the application is impersonating via <identity impersonate="true"/>, the identity will be the anonymous user (typically IUSR_MACHINENAME) or the authenticated request user.
To grant ASP.NET access to a file, right-click the file in File Explorer, choose "Properties" and select the Security tab. Click "Add" to add the appropriate user or group. Highlight the ASP.NET account, and check the boxes for the desired access.
Source Error:
Line 34: if( !Directory.Exists(path))
Line 35: Directory.CreateDirectory(path);
Line 36: file.SaveAs(path);
Line 37: }
Line 38:
Source File: C:\Users\****\Documents\Visual Studio 2010\Projects\Solution\Project\Controllers\UploadTestController.cs Line: 36
Stack Trace:
[UnauthorizedAccessException: Access to the path 'C:\Sites\ClosedBeta\Content\uploads\test.csv' is denied.]
System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) +10760710
System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost) +1352
System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy) +60
System.IO.FileStream..ctor(String path, FileMode mode) +55
System.Web.HttpPostedFile.SaveAs(String filename) +94
System.Web.HttpPostedFileWrapper.SaveAs(String filename) +9
Project.Controllers.UploadTestController.Upload(HttpPostedFileBase file) in C:\Users\****\Documents\Visual Studio 2010\Projects\Solution\Project\Controllers\UploadTestController.cs:36
lambda_method(Closure , ControllerBase , Object[] ) +180
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +14
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +214
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +27
System.Web.Mvc.<>c__DisplayClass15.<InvokeActionMethodWithFilters>b__12() +55
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +253
System.Web.Mvc.<>c__DisplayClass17.<InvokeActionMethodWithFilters>b__14() +21
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +191
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +324
System.Web.Mvc.Controller.ExecuteCore() +106
System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +91
System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +10
System.Web.Mvc.<>c__DisplayClassb.<BeginProcessRequest>b__5() +34
System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +19
System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +10
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.<>c__DisplayClasse.<EndProcessRequest>b__d() +48
System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f) +7
System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +22
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +60
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9629708
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
Any adivce would be apreciated
I think that the problem was simply that I needed to wait a bit for the permissions to take effect.
After Comming back to the same code the next day, it worked perfectly.
simply go though iis check is IISUSER and IUSR_ has permission to read and write
Generally plesk panel and cpanel add default permission to read list and write but in some cases something goes wrong and u need to setup the right permission.
So you have 2 way to achive your goal:
If you have access to iss do it by youself
or
Ask to your hosting company to setup write and read permission to this particular folder.

upload pictures

Hello everyone i have a problem with my website. When i upload pics using my local host, it works fine but when i try to upload the pics from the internet, i have the following error message:
Server Error in '/please-god' Application.
Access to the path 'D:\Hosting\4423045\html\please-god\UploadedImages\3.jpg' is denied.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.UnauthorizedAccessException: Access to the path 'D:\Hosting\4423045\html\please-god\UploadedImages\3.jpg' is denied.
ASP.NET is not authorized to access the requested resource. Consider granting access rights to the resource to the ASP.NET request identity. ASP.NET has a base process identity (typically {MACHINE}\ASPNET on IIS 5 or Network Service on IIS 6) that is used if the application is not impersonating. If the application is impersonating via , the identity will be the anonymous user (typically IUSR_MACHINENAME) or the authenticated request user.
To grant ASP.NET access to a file, right-click the file in Explorer, choose "Properties" and select the Security tab. Click "Add" to add the appropriate user or group. Highlight the ASP.NET account, and check the boxes for the desired access.
Source Error:
Line 21: If imageUpload.HasFile Then
Line 22: Dim baseDirectory As String = Server.MapPath("~/UploadedImages/")
Line 23: imageUpload.SaveAs(baseDirectory & pictureIDJustAdded & ".jpg")
Line 24: End If
Line 25: End If
Source File: D:\Hosting\4423045\html\please-god\PhotoAdmin\Default.aspx.vb Line: 23
Stack Trace:
[UnauthorizedAccessException: Access to the path 'D:\Hosting\4423045\html\please-god\UploadedImages\3.jpg' is denied.]
System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) +7715167
System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy) +1162
System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy) +61
System.IO.FileStream..ctor(String path, FileMode mode) +55
System.Web.HttpPostedFile.SaveAs(String filename) +99
System.Web.UI.WebControls.FileUpload.SaveAs(String filename) +23
PhotoAdmin_Default.dvPictureInsert_ItemInserted(Object sender, DetailsViewInsertedEventArgs e) in D:\Hosting\4423045\html\please-god\PhotoAdmin\Default.aspx.vb:23
System.Web.UI.WebControls.DetailsView.OnItemInserted(DetailsViewInsertedEventArgs e) +108
System.Web.UI.WebControls.DetailsView.HandleInsertCallback(Int32 affectedRows, Exception ex) +69
System.Web.UI.DataSourceView.Insert(IDictionary values, DataSourceViewOperationCallback callback) +134
System.Web.UI.WebControls.DetailsView.HandleInsert(String commandArg, Boolean causesValidation) +274
System.Web.UI.WebControls.DetailsView.HandleEvent(EventArgs e, Boolean causesValidation, String validationGroup) +676
System.Web.UI.WebControls.DetailsView.OnBubbleEvent(Object source, EventArgs e) +95
System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args) +37
System.Web.UI.WebControls.DetailsViewRow.OnBubbleEvent(Object source, EventArgs e) +113
System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args) +37
System.Web.UI.WebControls.LinkButton.OnCommand(CommandEventArgs e) +118
System.Web.UI.WebControls.LinkButton.RaisePostBackEvent(String eventArgument) +135
System.Web.UI.WebControls.LinkButton.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +175
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1565
You need to give permissions to the IIS user to that directory. The error message provides information on what to do, but there is more info below
More info here - http://www.webdeveloper.com/forum/showthread.php?t=131624
or
https://stackoverflow.com/search?q=Exception+Details%3A+System.UnauthorizedAccessException

Resources