I am using an FTPClient library to transfer files from a Windows share to an FTP server.
The SendFile method of the library uses the following code:
FileStream stream = new FileStream(localFileName, FileMode.Open);
This results in a System.UnauthorizedAccessException being thrown, however I am able to open, rename, and move the file using Windows Explorer under the same user account which the code is being executed.
Can anyone tell me why this is happening?
Edit:
The strange thing is that I can access other files on the share which have been granted the same NTFS permissions as the one that I can't.
This is also a Windows forms app.
Update:
Still no luck with this. I am able to read the file using a StreamReader but not a file stream. I can't understand why the two behave differently.
Are you sure it's the same user account?
Can you try something like
MessageBox.Show(WindowsIdentity.GetCurrent().Name);
?
Also, are you sure the file isn't read-only? Do you need write access to the file?
Otherwise you could try:
FileStream stream = new FileStream(localFileName, FileMode.Open, FileAccess.Read);
The process that is running your code does not have permissions on the file.
Is it part of a web application - if so you need to give access to the ASPNET account.
Give permission to 'everyone' on the file, and see if it still has problems.
Is your project being run from a network drive? If so that that will mean it runs in a restricuted priviliges mode that could cause this. Try copying the project to your C drive and running it again.
It's near FileSecurity class.
See at FileSecurity class
and try:
// Get a FileSecurity object that represents the
// current security settings.
FileSecurity fSecurity = File.GetAccessControl(localFileName);
// Add the FileSystemAccessRule to the security settings.
fSecurity.AddAccessRule(new FileSystemAccessRule("DOMAIN\USERNAME",
FileSystemRights.ReadData, AccessControlType.Allow));
// Set the new access settings.
File.SetAccessControl(localFileName, fSecurity);
1) NTFS permissions on the physical directory using explorer
2) Within the IIS MMC console FTP Site to allow read/write on the FTP folder
3) Ensure that the FTP Site or virtual directory actually exists, when checking the above step
http://www.eggheadcafe.com/forumarchives/inetserveriisftp/Jan2006/post25322215.asp
Related
I want to open file for append on Windows 7 host using C#/.NET. I want to use usual file output operations for this purpose. I found such solution:
FileStream trace_fd = new FileStream(r"c:\temp\testlog.txt",
FileMode.Append,
FileAccess.Write,
FileShare.ReadWrite)
My tracefile is readable even if my program with line above is up and running. I don't have exception that file is used by another process anymore from proper code like this:
FileStream good_logreader_fd = new FileStream("c:\temp\testlog.txt",
FileMode.Read,
FileAccess.Read,
FileShare.ReadWrite)
Then I have another program (buggy log scanner) with such line:
FileStream bad_logreader_fd = new FileStream("c:\temp\testlog.txt",
FileMode.Read,
FileAccess.Read,
FileShare.None)
Such line is obviously a bug for log scanner. If my program is not running then buggy logscaner will get exclusive lock and subsequent runs of my program will fail to get fd for trace file.
My question is what can I do to prevent such horrific scenario from happening.
E.g. can I set file permissions for the tracefile to prevent anyone from taking exclusive lock? If yes then how? Anything else which can protect my program from buggy log scanner problem? Note that I have to keep the same trace filename between my program runs.
You can not set permissions to allow any access to a file, but somehow restrict FileShare.None as file sharing mode is not related to access permissions.
Permissions give a process (based on account it runs under) access to a file/resource. If access granted process can open file with whatever share mode it desires. If this share mode does not conflict with existing share modes on the file request succeeds and now file will have this share mode (combined with previous one). See CreateFile- dwShareMode section for details.
In your case log reader needs to have permissions to open file, so it will be able to set ShareMode.None if it the first process to open file. As devshorts says there is not much you can do short of changing offending process OR hacking file access methods (search for "hook CreateFile").
Side note: if your log reader runs under the same account as other processes permissions will not help for one additional reason - as there is no "per process" permissions in Windows and all processes will share the same user's permissions.
As far as I know you can't prevent someone else from trying to open the file in another file access mode without modifying their code.
I have a folder that I want to protect its contents,
I'm denying full control to it by this code:
void changeFolderPermission(string folder, FileSystemRights rights, AccessControlType type)
{
DirectoryInfo myDirInfo = new DirectoryInfo(folder);
DirectorySecurity myDirSecurity = myDirInfo.GetAccessControl();
string user = System.Environment.UserName;
myDirSecurity.ResetAccessRule(new FileSystemAccessRule(user, rights, type));
myDirInfo.SetAccessControl(myDirSecurity);
}
I'm using it like this:
changeFolderPermission(FolderName, FileSystemRights.FullControl, AccessControlType.Deny);
It's working fine, I mean, when i try to open the folder, it won't let me.
Problem is, I could easily remove that permission by right clicking on the folder,
going to security, look for that special permission and just deleting it ..
is there a way to prevent someone from doing this ?
I want the folder to be fully secured.
Now I know that there's something like this:
hangeFolderPermission(FolderName, FileSystemRights.ChangePermissions, AccessControlType.Deny);
but I'm still being able to change the permissions.
any help would be appreciated .. thanx alot in advance .. :)
You can not prevent a user with admin rights from accessing a folder or file.
If the user does not have admin rights, then set the permissions (via an admin account) to deny the user access. Properly configured permissions will prevent the non-admin user from accessing the folder/file.
You never said anything in your original post about sending the folder to other people. Presumably this sending mechanism involves email, ftp, etc to ANOTHER COMPUTER. Assumption #2 is that your C# program is what will be reading the contents of said folder.
In this case its simple, create a password-protected zip file of your directory and send that. Then embed the password within your C# code and open the zip file and read its contents.
There are several really good zip manipulation libraries out there such as dotnetzip and #ziplib
I am doing an project from my school and I am trying to delete a file from Windows XP.
However, I encounter this error, even after I set the attribute of the file.
Access to the path is denied"
The file is in C:\Document and Settings\%user%\Local Settings\Temp.
How can this be solved?
if(File.Exists(filePath))
{
FileSecurity sec = File.GetAccessControl(filePath);
sec.AddAccessRule(new FileSystemAccessRule(Environment.UserName,
FileSystemRights.FullControl, AccessControlType.Allow));
File.SetAccessControl(filePath, sec);
File.SetAttributes(filePath, FileAttributes.Normal);
File.Delete(filePath);
}
FileSecurity sets permissions on the file itself. Thats all great but it doesn't mean you have the permission to Delete it. Try running your app as an administrator and see if that makes a difference.
That means that another program is using the file.
You must close the file (or the entire program) before you can delete it.
If your program uses the file, make sure to close (not cross) the streams.
Check whether you have "admin" or related permission to delete the files.
If you have admin authority, then check whether the file which you have mentioned has other "rights" Ex: few MS files cannot be deleted.
Check whether you have specified the right file name.
If you have verified all these then this file either you have opened it or in your code you have not closed it to delete it.
Even if the above solution doesn't work then this file is either corrupted or some other user or yourself are still using this file which is not closed.
So far, the code block is okay.
However, keep in mind the below things:
a. In case of Windows XP, with the user you logged in - make sure that the user is in administrator group and the user will have admin access, so any application running by the user will have admin privileges.
b. In case of other updated Windows like Vista, Windows 7, try running the application as an administrator ( right click on application and the click on "run as administrator" from the pop-up, while checking in development time - run your IDE as administrator ).
Hope this would be helpful.
I have been trying to lock a file so that other cloned services cannot access the file. I then read the file, and then move the file when finished. The Move is allowed by using FileShare.Delete.
However in later testing, we found that this approach does not work if we are looking at a network share. I appreciate my approach may not have been the best, but my specific question is:
Why does the below demo work against the local file, but not against the network file?
The more specific you can be the better, as I've found very little information in my searches that indicates network shares behave differently to local disks.
string sourceFile = #"C:\TestFile.txt";
string localPath = #"C:\MyLocalFolder\TestFile.txt";
string networkPath = #"\\MyMachine\MyNetworkFolder\TestFile.txt";
File.WriteAllText(sourceFile, "Test data");
if (!File.Exists(localPath))
File.Copy(sourceFile, localPath);
foreach (string path in new string[] { localPath, networkPath })
{
using (FileStream fsLock = File.Open(path, FileMode.Open, FileAccess.ReadWrite, (FileShare.Read | FileShare.Delete)))
{
string target = path + ".out";
File.Move(path, target); //This is the point of failure, when working with networkPath
if (File.Exists(target))
File.Delete(target);
}
if (!File.Exists(path))
File.Copy(sourceFile, path);
}
EDIT: It's worth mentioning that if you wish to move the file from one network share, to another network share while the lock is in place, this works. The problem only seems to occur when moving a file within the same file share while it is locked.
I believe System.IO.File.Open() maps to the Win32 API function CreateFile(). In Microsoft's documentation for this function [ http://msdn.microsoft.com/en-us/library/aa363858(v=vs.85).aspx ], it mentions the following:
Windows Server 2003 and Windows XP/2000: A sharing violation occurs if an attempt is made to open a file or directory for deletion on a remote computer when the value of the dwDesiredAccess parameter is the DELETE access flag (0x00010000) OR'ed with any other access flag, and the remote file or directory has not been opened with FILE_SHARE_DELETE. To avoid the sharing violation in this scenario, open the remote file or directory with the DELETE access right only, or call DeleteFile without first opening the file or directory for deletion.
According to this, you would have to pass DELETE as the FileAccess parameter to IO.File.Open(). Unfortunately, the DELETE enumeration was not included as an option.
This problem only pertains to Windows 2003 and earlier. I have tested your code on Windows 2008 R2 SP1, and it works fine. So it is possible that it would also work on Windows 2008 as well.
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.