System.Unauthorized Exception - c#

*
Exception =System.Net.WebException: Access to the path
'c:\windows\system32\inetsrv\Dialer' is denied. --->
System.UnauthorizedAccessException: Access to the path
'c:\windows\system32\inetsrv\Dialer' 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, FileShare share, Int32 bufferSize, FileOptions options, String
msgPath, Boolean bFromProxy) at System.IO.FileStream..ctor(String
path, FileMode mode, FileAccess access, FileShare share) at
System.Net.FileWebStream..ctor(FileWebRequest request, String path,
FileMode mode, FileAccess access, FileShare sharing) at
System.Net.FileWebRequest.GetRequestStreamCallback(Object state)
--- End of inner exception stack trace --- at System.Net.WebClient.UploadDataInternal(Uri address, String method,
Byte[] data, WebRequest& request) at
System.Net.WebClient.UploadString(Uri address, String method, String
data)
*
Code where the exception is occurring
using (var writer = new StringWriter())
{
JsonSerializer.Create().Serialize(writer, payLoad);
var result =client.UploadString(commDialerApiUrl,writer.ToString());
return ((T)JsonConvert.DeserializeObject(result, typeof(T)));
}
I know the code above is not ideal, however I just need to understand why even an attempt to access is made. Can anyone provide some insight please?

All right, the issue was very simple. The code was trying to make a Restful post to a blank Uri. Since the Uri was blank webclient was trying to resolve the call to a file (having the same name as the service) in inetpub.
Since no such file path was invalid, thus the i/o error.

Related

Dot Net new console creation on VS Code

Whenever I go to vscode's terminal and type
dotnet new console
it gives me an error
Error while processing file /content/ConsoleApplication-CSharp/Company.ConsoleApplication1.csproj
System.UnauthorizedAccessException: Access to the path '/Users/zohaibarsalan/Documents/programming/c#/learningc#/learningc#.csproj' is denied.
---> System.IO.IOException: Operation not permitted
--- End of inner exception stack trace ---
at Interop.ThrowExceptionForIoErrno(ErrorInfo errorInfo, String path, Boolean isDirectory, Func`2 errorRewriter)
at Microsoft.Win32.SafeHandles.SafeFileHandle.Open(String path, OpenFlags flags, Int32 mode)
at System.IO.FileStream.OpenHandle(FileMode mode, FileShare share, FileOptions options)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize)
at System.IO.File.Create(String path)
at Microsoft.TemplateEngine.Utils.PhysicalFileSystem.CreateFile(String path)
at Microsoft.TemplateEngine.Core.Util.Orchestrator.ProcessFile(IFile sourceFile, String sourceRel, String targetDir, IGlobalRunSpec spec, IProcessor fallback, IEnumerable`1 fileGlobProcessors, IReadOnlyList`1 locOperations)
how can I fix this?
I have installed dot net from Microsoft, so do I need to delete it, and if so how?
or do I have to change some settings?
This also happens on the terminal.
BTW this is on a MAC

Open locked file with OpenXML in read only mode

When I try to open a file that is locked, like this:
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
... code stripped for clarity ...
// false stands for read only mode
spreadsheetDocument_ = SpreadsheetDocument.Open(fileName_, false);
I get this exception:
System.IO.IOException: 'The process cannot access the file 'file.xlsx' because it is being used by another process.'
Full stack trace:
System.IO.IOException
HResult=0x80070020
Message=The process cannot access the file 'file.xlsx' because it is being used by another process.
Source=mscorlib
StackTrace:
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)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, Boolean useAsync)
at MS.Internal.IO.Zip.ZipArchive.OpenOnFile(String path, FileMode mode, FileAccess access, FileShare share, Boolean streaming)
at System.IO.Packaging.ZipPackage..ctor(String path, FileMode mode, FileAccess access, FileShare share, Boolean streaming)
at System.IO.Packaging.Package.Open(String path, FileMode packageMode, FileAccess packageAccess, FileShare packageShare, Boolean streaming)
at DocumentFormat.OpenXml.Packaging.OpenXmlPackage.OpenCore(String path, Boolean readWriteMode)
at DocumentFormat.OpenXml.Packaging.SpreadsheetDocument.Open(String path, Boolean isEditable, OpenSettings openSettings)
at DocumentFormat.OpenXml.Packaging.SpreadsheetDocument.Open(String path, Boolean isEditable)
How can I open the file in read only mode and ignore the lock flag? I also want to avoid creating a lock flag if the file is not open in another program, so that the file can be edited further.
Try to passing a stream instead of string (file path). You can also use a File stream class to open the Excel file.
Console app snippet:
static void Main(string[] args)
{
using (var fileStream = new FileStream(#"path", FileMode.Open,FileAccess.Read, FileShare.ReadWrite))
{
using (var spreadSheetDocument = SpreadsheetDocument.Open(fileStream, false))
{
//Implementation
}
}
}
Source: OpenXML and opening a file in Read only mode

IIS 7 Access to the path is denied when trying to generate report

We are getting this error message upon trying to generate a report not accessing a file. We are using IIS 7.
XXX is located on a different server than the web server.
2014-10-24 11:04:13,287 [5] ERROR FOUNDATION [(null)] - Access to the path '\\XXX \file2022.pdf' is denied.
System.UnauthorizedAccessException: Access to the path '\\XXX\file.pdf' 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)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy)
at System.IO.FileStream..ctor(String path, FileMode mode)
at CrystalDecisions.CrystalReports.Engine.FormatEngine.WriteStreamToFile(Stream stream, String filename)
at CrystalDecisions.CrystalReports.Engine.FormatEngine.ExportStreamToFile(Stream stream, DiskFileDestinationOptions options)
at CrystalDecisions.CrystalReports.Engine.FormatEngine.Export(ExportRequestContext reqContext)
at CrystalDecisions.CrystalReports.Engine.ReportDocument.ExportToDisk(ExportFormatType formatType, String fileName)
at GlobalFunctions.GenerateCrystalReport(String reportFileName, String outputFileName, List`1 params) in C:\NetProjects\branches\R7\GUIs\Foundation\App_Code\GlobalFunctions.vb:line 347
If you must access files like this make sure your Application Pool is running as a domain user with read permission to that location.

Substring on SSIS Variable expression

I Have SSIS Variable Expression like this,
#[System::PackageName]+","+
#[System::SourceName]+","+
(DT_STR,15,1252) #[System::ErrorCode]+","+
#[System::ErrorDescription]+","+
(RIGHT((DT_WSTR,4)
DATEPART("yyyy",GetDate()),4)+"/"+
RIGHT("0"+(DT_WSTR , 2)
DATEPART("mm", GetDate()),2)+"/"+
RIGHT("0"+(DT_WSTR,2)
DATEPART("dd",GetDate()),2)+"_"+
RIGHT("0"+(DT_WSTR,2)
DATEPART("HH",GetDate()),2)+":"+
RIGHT("0"+(DT_WSTR,2)
DATEPART("MM",GetDate()),2)+":"+
RIGHT("0"+(DT_WSTR,2)
DATEPART("SS",GetDate()),2))+","+
#[System::MachineName]
Now I want to get some string from #[System::ErrorDescription] which located before at , here's the sample of the #[System::ErrorDescription] value
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.IO.DirectoryNotFoundException: Could not find a part of the path 'D:\blablablabl\yes.txt'.
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)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize)
at System.Xml.XmlDownloadManager.GetStream(Uri uri, ICredentials credentials)
at System.Xml.XmlUrlResolver.GetEntity(Uri absoluteUri, String role, Type ofObjectToReturn)
at System.Xml.XmlTextReaderImpl.OpenUrlDelegate(Object xmlResolver)
at System.Threading.CompressedStack.runTryCode(Object userData)
at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
at System.Threading.CompressedStack.Run(CompressedStack compressedStack, ContextCallback callback, Object state)
what i've done is write the substring code on my variable expressions :
SUBSTRING(#[System::ErrorDescription], 1, FINDSTRING(#[System::ErrorDescription], "at", 1)-1)+","+
but its always give me an error , that substring value cannot be negative, whats wrong with my code?
If the result of FINDSTRING(#[System::ErrorDescription], "at", 1) is zero (i.e. string not found) then the last parameter to your substring expression becomes -1. It's a common problem.
Perhaps you could try evaluating whether it is zero, and only use Findstring if it isn't. I have split the expression below for clarity, but it should all be on one line. I don't have SSIS to test but see if it works.
I don't think you've posted your full expression but this should give you the idea.
FINDSTRING(#[System::ErrorDescription], "at", 1)==0
?
"Nothing Found"
:
SUBSTRING(
#[System::ErrorDescription],
1,
FINDSTRING(#[System::ErrorDescription], "at", 1)-1
)
Here's a link that describes conditional:
http://msdn.microsoft.com/en-us/library/ms141680.aspx
I'm not convinced this is the full story, but try it and it will flush out your next issue.

Not able to upload a file on server

I am trying to upload an image.it works fine when i do it from my localhost but when i published it it throw an error from server:
When I use this code :
public string ImagePath(HttpPostedFileBase imgfile)
{
var path = "";
// code for saving the image file to a physical location.
var fileName = Path.GetFileName(imgfile.FileName);
path = Path.Combine(HttpContext.Server.MapPath("~/Images/Sections/Developer/ClientLogo"), fileName);
string fileNameWithoutExtension = System.IO.Path.GetFileNameWithoutExtension(imgfile.FileName);
int iteration = 1;
while (System.IO.File.Exists((path)))
{
fileName = string.Concat(fileNameWithoutExtension, "-", iteration, System.IO.Path.GetExtension(imgfile.FileName));
path = Path.Combine(HttpContext.Server.MapPath("~/Images/Sections/Developer/ClientLogo"), fileName);
iteration++;
}
imgfile.SaveAs(path);
// prepare a relative path to be stored in the database and used to display later on.
path = Url.Content(Path.Combine("~/Images/Sections/Developer/ClientLogo", fileName));
return path;
}
Error is
System.UnauthorizedAccessException: Access to the path 'D:\InetPub\vhosts\xx.com\httpdocs\Images\Sections\Developer\ClientLogo\circle-small-empty.18x18.png' 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, Boolean checkHost) at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy) at System.IO.FileStream..ctor(String path, FileMode mode) at System.Web.HttpPostedFile.SaveAs(String filename) at System.Web.HttpPostedFileWrapper.SaveAs(String filename) at xx.CorporateSite.Controllers.DeveloperController.ImagePath(HttpPostedFileBase imgfile)
And when I use Server.MapPath instead of HttpContext.Server.MapPath it throw different error:
Error is:
System.IO.DirectoryNotFoundException: Could not find a part of the path 'D:\InetPub\vhosts\xx.com\httpdocs\Images\Sections\Developer\ClientLogo\demo.png'. 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) at System.IO.FileStream..ctor(String path, FileMode mode) at System.Web.HttpPostedFile.SaveAs(String filename) at System.Web.HttpPostedFileWrapper.SaveAs(String filename) at xx.CorporateSite.Controllers.DeveloperController.ImagePath(HttpPostedFileBase imgfile)
I tried to change the permission from my localhost but nothing is working...Please suggest me something
Your web application does not have permission to write to the location where you're trying to save the image. This is often handled by adding an entry to your web.config which points to a folder where all uploads are saved
<appSettings>
...
<add key="uploadPath" value="C:\Uploads"/>
...
</appSettings>
and then in your code you would read that configuration entry to identify the path where the image will be saved:
....
string path = ConfigurationManager.AppSettings["uploadPath"];
string filePath = Path.Combine(path, fileName);
....
And then in order to save the files to this directory, you would need to set permissions on the directory so that the user that the web application is running as has Write permissions on that directory. This will allow you to write files from the web application to that folder.
This way, you, as the developer, are not dictating where the files go. The system administrator can decide both where the files go, and what permissions are necessary to support your web application.
Check to see if the folder's Read-Only attribute is active. If it is uncheck it in the properties of the folder if this is a windows machine.
If it keeps reverting you may need to take ownership of the folder by going to security->advanced->effective permissions->click select...->put in your username and check full control->then click ok out.

Categories

Resources