How do I create a bitmap object using a UNC path? - c#

I am trying to do something like this
Bitmap img = new Bitmap("\\\\server\\folder\\picture.jpg");
which fails every time.
I know I have permission to read the file because I can manually access it.
In general, I would like to know how to work with UNC paths in C#.

That path is valid. Also, with string literals in C# you can declare them like this #".\MyPath\Doesn'tNeed\DoubleSlashes\Because\IUsed#\file.txt"
This tutorial will show you how to access a UNC path with credentials (which you probably need) http://www.codeproject.com/Articles/43091/Connect-to-a-UNC-Path-with-Credentials
Keep in mind that just because the user on Machine A has permissions to access files on Machine B doesn't mean they can do so without entering their credentials.

Account that code runs under on your ASP.Net server does not seem to have permissions to read this file. Some possible reasons:
one-hop authentication (if you run code with impersonation)
anonymous account does not have permissions on "\server"
You need to figure out what account code runs under before taking next steps to grant access to it.

Related

Server.MapPath Access is denied On Azure

I am exporting an excel using c# code and spreadsheetlight dll.
I am trying to insert a picture into excel, everything works well on local machine but on live web site it gives following error
Access to the path 'F:\sitesroot\0\Images\Logo.png' is denied
My c# code.
string filePath = Server.MapPath("~/Images/Logo.png");
SLPicture pic = new SLPicture(filePath); //SLPicture - An inbuilt class for inserting image
Currently what I am doing is manually providing access rights on IIS server but which is not the correct way to go since each time I upload the service I have to redo that again and again
Any expert advice - How I can provide access right through code?
Or How to get rid of this error.
Thanks.
Assuming you are using Cloud services...
You are supposed to use Local Storage for this (http://msdn.microsoft.com/en-us/library/windowsazure/ee758708.aspx).
Basically;
In your Cloud project, go to the properties for the Role and select Local Storage.
Add a new local storage and give it a name, i.e. "foo" and a maximum size. If this is for temporary processing rather than caching, you probably want to tick "Clean on role recycle".
In your code call RoleEnvironment.GetLocalResource("foo") to get the folder name you can use and then do something like Path.Combine("path","Logo.png") to get a file name which you can then write to.

File.Exists() always returns false on IIS

The file path that I'm checking with File.Exists() resides on a mapped drive (Z:\hello.txt). The code runs fine in debug environment, however in IIS, it always returns false
var fullFileName = string.Format("{0}\\{1}", ConfigurationManager.AppSettings["FileName"], fileName);
if (System.IO.File.Exists(fullFileName))
Why is this so, and how can I workaround this?
I have granted everyone full read/write permissions in that mapped drive
EDIT:
I tried deleting the file via \\192.168.1.12\Examples\Files\2.xml and I get the same result. It doesn't detect the file on IIS, but works fine on debug
I think your application do not has permission on "Z:"
Is "Z:" network disk?
I have had similar issues using network mapped drives, when running debug code application works perfectly and when running release version application cannot find the file.
If the files are stored on the same server as the application is deployed we found a solution by storing the local drive directory location of the mapped drive for example Z:\files\ could be E:\folder\folder1\
If the application is deployed on a separate server we found using the full network name works for example \\server1\folder\
I hope this proves helpful to you.
Your web application is running under a certain security context and you need to find out what context this is. If it's a normal user, open a command prompt as the user (using the runas tool), map the required drive using the command prompt (be sure to use the /persistent:yes flag)
Alternatively why can't you just use a UNC path (\\serverName\shareName) and avoid all this nonsense?
EDIT: 2013-05-27
To troubleshoot this, create a new application pool, based on whatever app pool you want. Then set the identity that this pool runs under as shown in the attached screenshot.
Make sure that this user has the correct privileges on the file share and then retest it
May be you should use Path.DirectorySeparatorChar

C# ASP.NET File.OpenRead from UNC path: "Access to path.....is denied."

I'm attempting to read a PDF from a UNC path, i.e. \10.32.16.24\repositories\repository0001\VOL00001\ktappb01_024655001_0.PDF
My virtual directory ASP.NET site is being run under IUSR_machine_name.
Has anonymous access enabled as well.
I gave IUSR_machine_name full rights to the UNC share and as I step through my ASP.NET page's code behind onto the File.OpenRead(filepath) method, it throws an exception: "Access to path \10.32.16.24\repositories\repository0001\VOL00001\ktappb01_024655001_0.PDF is denied".
I tried granting the ASPNET user full rights to the share as well with the same result.
At this point I'm completely lost for a resolution.
I'm running IIS6.
On both machines security eventlog, check what user has been denied access. It is most likely a different user.
I was able to find the user by logging it. I'd made a stupid error in my code that wasn't giving me the result I was assuming I was going to get.

Access denied error

I am trying to delete the excel file from a specipic location . but can't deleting. having error :
Access to the path 'C:\mypath\sample.xlsx' is denied.
I write a code as :
protected void imgbtnImport_Click(object sender, ImageClickEventArgs e)
{
try
{
string strApplicationPath = HttpContext.Current.Request.MapPath(HttpContext.Current.Request.ApplicationPath);
string strXLStoredDirectoryPath = strApplicationPath + "/Information Documents/";
DirectoryInfo di = new DirectoryInfo(strXLStoredDirectoryPath);
string fileName = flUpldSelectFile.FileName;
if (!File.Exists(strXLStoredDirectoryPath))
{
Directory.CreateDirectory(strXLStoredDirectoryPath);
di.Attributes = FileAttributes.Normal;
}
string strCreateXLFileDestinationPath = strXLStoredDirectoryPath + fileName;
if (File.Exists(strCreateXLFileDestinationPath))
{
File.Delete(strCreateXLFileDestinationPath);
}
flUpldSelectFile.SaveAs(strCreateXLFileDestinationPath);
di.Attributes = FileAttributes.ReadOnly;
}
catch (Exception)
{
throw;
}
}
please guide.........
-***********************************************************************
Still problem there . it is not resolved . getting UnauthorizedAccessException. as access denied to deleting file. I m tired now . please help; I tried many things..please help
-***********************************************************************
Is may be iffect of VSS ? i am using that
UPDATE:
Part of your issue might be what is saving/creating this file. If you're using a built in "Save" or "SaveAs" feature the underlying file stream might still have a lock on the file. writing your own save logic with a FileStream wrapped in a Using statement will help dispose the stream right when you're done thus allowing you to further manipulate the file within the same context.
if flUpldSelectFile.SaveAs(strCreateXLFileDestinationPath); is the only logic that saves the file then get rid of the built in SaveAs functionality. write your own save logic using a FileStream wrapped in a Using block.
In your example i can't see what flUpldSelectFile is so i am assuming it is a System.Web.UI.WebControls.FileUpload control. Here is an example of rolling your own save logic.
using (FileStream fs = new FileStream(strCreateXLFileDestinationPath, FileMode.Create))
{
byte[] buffer = flUpldSelectFile.FileBytes;
fs.Write(buffer, 0, buffer.Length);
}
As stated previously, use this tool to find out if there is a lock on the file by another process.
ORIGINAL
Pop open this wonderful tool and search for that file to see who/what has it locked
http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx
(source: microsoft.com)
If your code is working under IIS , Note that ASPNET user doesn't have access to computer files, you should give access to it, that is not recommended, or store you files in the place where ASPNET user have access
see here
Try a combination of these 2 steps:
Set the IIS application pool to run under an account with privileges such as a domain account or local user account (not a default account like local service or local system). Instructions for IIS7.
Turn impersonation on in the web.config file, in the <system.web> section:
<identity impersonate="true"/>
<identity impersonate="true" userName="contoso\Jane" password="password"/>
I think the message is clear, you do not have authorization to delete the file or it is opened by another application. I bet 2$ you can't delete the file manually either.
As others have said, this is because IIS runs your application as a user with restricted access rights. This is a wise security precaution, so that your system is less vulnerable to malicious attacks.
What you need to do is to give the ASPNET user access to the specific folder. You do that from the security tab in the properties of a folder. The user you need to give full control to depends on the version of IIS you are using. In Windows XP it is ASPNET. In Windows Server 2003, 2008 and Windows Vista, 7 it is NETWORK_SERVICE.
See also this question for more details.
Make sure the file isn't opened or
locked by another user/process.
Make sure ASPNET user has access on the file\folder (check the file\folder's property using windows explorer and go to security tab. check if ASPNET user is added there).
One of two things are happening. Either the file is already open, or the permission of the user running IIS does not have the proper permissions.
Either way, this utility ProcMon: Proc Mon
will help you determine the issue. Run ProcMon, kick off your process to try and delete the file. Then go back to procmon. Hit Ctrl-E to turn off the capture, then Ctrl-F to find. Enter the name of the file you're trying to delete. Then once you've found the correct line with the access denied (or similar error) Double click on the the line to get further information. When you click on the Process tab, it will show you the exact user that is trying to delete the file.
So, if it is a file permission issue, you now know the exact user, and can therefore go to the file system right click on the folder that houses the file you are trying to delete, and grant that user permissions to read/write/update that folder.
Second, if the file is locked open instead of a permissions issue, you will have to find out what process is holding open the file. If you are also writing this file in another part of your code, perhaps you are not closing it properly or releasing the object reference.
Have you verified that the file does not have the read-only attribute set?
I don't think we have enough info to be helpful. What is the security context (identity) during the call to Delete? Is the application impersonating the end user? If it is, how are they authenticated? If by Windows / Active Directory, then you'll need to verify that user's access rights to the specific file. If by Forms login, then you should probably not impersonate and verify that the AppPool's security context has the appropriate access rights.

Is FileInfo.Copy accross network good solution? Is CAS required?

Seems that everything I do involves win services copying files across servers. I seem to get a lot of security & securityaccess type exceptions and never fully understand the causes. I am wondering if fileinfo or file.copy is a good solution or if there is a better. Is there a particular attribute I should be using or something to avoid these errors? Issue is not account or password related. example are \ipaddress\sharename \ipaddress\drive\path using domain accounts.
---Added Specific example.---
- I log on to serverA as domain\username. (including domain name)
- I open file eplorer in the address bar enter \\serverB\c$\folder hit enter, I right-click, create new file. No problem.
- I install service, go to properties select Log On, This Account and set the username as domain\username (including the domain name) same password I logged onto serverA with. It accepts it no problem.
Application does a FileSystemWatcher on \\serverA and copy to \\serverB when changed to keep the config files in sync.
private void CopyNewFileToClone()
{
FileInfo OriginalConfigFile = new FileInfo(Path.Combine(ConfigurationManager.AppSettings.Get("directoryToWatch"), ConfigurationManager.AppSettings.Get("fileToWatch")));
FileInfo CloneConfigFile = new FileInfo(Path.Combine(ConfigurationManager.AppSettings.Get("directoryToCopyTo"), ConfigurationManager.AppSettings.Get("fileToCopyTo")));
FileInfo tmp = new FileInfo(Path.Combine(CloneConfigFile.DirectoryName,"~" + CloneConfigFile.Name));
OriginalConfigFile.CopyTo(tmp.FullName, true);
tmp.CopyTo(CloneConfigFile.FullName, true);
tmp.Delete();
}
When I start the service I get Service cannot be started.
System.UnauthorizedAccessException: Access to the path '\\serverB\C$\folder\filename' is denied.
I use fileinfo to copy files from servers and it seems to work fine. If your sure it's not a account or password issue I would start looking at your DNS. If the network can't resolve what account is trying to access the network folder it won't matter if you are using a valid account. You may get lucky some/most of the time with cached accounts but there is no telling when it might not work and when it will work.
I would trace the network if you are getting a lot of broadcast messages for failed responses.
This was due to Code Access Security policy. Ran
c:\Windows\Microsoft.NET\Framework\v2.0.50727\CasPol.exe -af <path\application.exe>
and error resolved.
Adding as a installation step in all apps that need to write to HD, especially accross network via unc such as \server\share\file.

Categories