Can't delete a file in C# - unauthorized access exception - c#

In my ASP.Net web application, I have loaded one image on the HTML 5 canvas and allow the user to draw some graphics (rectangle box) over the images. Once the user has finished their drawings on the image I have to save the image back to the server with the same name at same location.
I am using AJAX to transmit the image data to the server. This part is done successfully.
In my server code, first I am trying to delete a file and then create a new file with the same name at same location.
So, When I am deleting the file, it is raising UnAuthorizedAccessException is handled by user code Access to the path 'D:\vs-2010projects\delete_sample\delete_sample\myimages\page_1.png' is denied.
Here is my Server Side C# Code...
[WebMethod()]
public static void UploadImage(string imageData)
{
byte[] data = Convert.FromBase64String(imageData);
if(File.Exists("D:\\vs-2010projects\\delete_sample\\delete_sample\\myimages\\page_1.png"))
{
File.Delete("D:\\vs-2010projects\\delete_sample\\delete_sample\\myimages\\page_1.png");
}
FileStream fs = new FileStream("D:\\vs-2010projects\\delete_sample\\delete_sample\\myimages\\page_1.png", FileMode.Create);
BinaryWriter bw = new BinaryWriter(fs);
bw.Write(data);
bw.Close();
}//UploadImage
Is there any way to delete a file?
Please guide me out of this issue.

First of all you should pack your stream statements into using clause that will automatically handle dispose action (even in case of exception) - it will save you a lot of time during debugging strange issues coming from not-closed streams
using(var fs = new FileStream(...))
{
using(var bw = new BinaryWriter(fs)
{
bw.Write(data);
}
}
Now the exception often comes because your current process does not have access rights for the file (can't delete file) - to solve it
add full permissions for your user
You can do this by finding the file in the Windows Explorer , checking its properties and under security tab you will find specific permissions.
For example if you host your page on IIS then it is identified as application pool identity which is either IIS_IUSRS or NETWORK SERVICE and those parties are usually not trusted (or not enough trusted to be able to delete file0

I presume, it has something to do with privilege. When a user tries to connect to your Web site, IIS assigns the connection to the IUSER_ComputerName account, which belongs to the Guests group. This group has security restrictions. Try to elevate access of IUSER_ComputerName.
More can be found here.

Related

Create a txt file asp.net application access denied

We tried creating a txt file using this code
using (StreamWriter _testData = new StreamWriter(Server.MapPath("~/data.txt"), true))
{
_testData.WriteLine(" asd"); // Write the file.
}
But we get the message Access to the path 'L:...\data.txt' is denied
Can this be done with Anonymous disabled and NETWORK SERVICE out of the users group in security of the folder?
Upd: We have a web application and we want to track the number of clicks on a certain button to get statistics for a month of its usage by each user, we cant use any database (not even access).
Is the best approach to create a txt file?
Maybe have a look to the IIS trust level.
http://technet.microsoft.com/en-us/library/cc754779.aspx
Depending on your configuration (above and medium included), you will not be able to write a file outside the application directory.
Here's my solution for appending data to a textfile as a log.
using (var stream = System.IO.File.AppendText(Server.MapPath("~/App_Data/data.txt")))
{
stream.WriteLine("testing..");
stream.Flush();
}
Put that in your Index() method on your controller and it will append "testing.." for each visit. Enjoy :)

A default path when downloading PDF file in computer/mobile phone

I created a PDF webapp where users are able to generate various type of PDF on both the computer and mobile phone. However, i run my program on a localhost and this is how i save my PDF based on my computer's file directory
var output = new FileStream(Path.Combine("C:\\Users\\apr13mpsip\\Downloads", filename), FileMode.Create);
However, when i publish my webapp onto azure, i wasn't able to download from both my computer and mobile phone. Therefore i believe that it could be due to my default file directory.
Hence i would like to ask how to do a default file directory for all computer and mobile phone?
Or could it be i left out something that is necessary when the webapp is published online
Thanks.
PS : I hardcoded a default file path in order for me to test my application on a localhost to ensure a perfect working condition. Therefore i'm finding a way to find a default common file directory for all mobile/computer users when they attempt to download the PDF instead of my usual hard-coded file path
UPDATE
I tried using the method Server.MapPath but receive some error.
var doc1 = new Document();
var filename = Server.MapPath("~/pdf") + "MyTestPDF" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".pdf";
// var output = new FileStream(Path.Combine("C:\\Users\\apr13mpsip\\Downloads", filename), FileMode.Create);
//iTextSharp.text.pdf.PdfWriter.GetInstance(doc1, output);
using (var output = File.Create(filename))
{
iTextSharp.text.pdf.PdfWriter.GetInstance(doc1, output);
}
doc1.Open();
This is the error i received
ObjectDisposedException was unhandled by user code
Cannot access a closed file.
When you write a Web Application you shall never use hard coded paths, and the last place where you should save files is C:\Users !! It does not matter whether this is Azure or not. It is general rule for any kind of web applications!
In your case I suggest that you create a folder within your application named pdf or something like that and save files there with the following code:
var fileName = Server.MapPath("~/pdf") + filename;
using (var output = File.Create(fileName) )
{
// do what you want with that stream
// usually generate the file and send to the end user
}
However there is even more efficient way. Use the Response.OutputStream and write the resulted PDF directly to the response. Will save you a lot of space on the local server, and the logic to delete unused generated files.

Uploading to Dropbox using Sharpbox API

I am attempting to use the Sharpbox API to upload a file to my dropbox account. However, when I attempt to upload a file to the "Public" folder, I get an error stating: "Couldn't retrieve child elements from the server".
I have followed the steps on page 10-11 of the documentation pdf and here is the code I am currently using (as a test I am trying to upload the token.txt file):
Public Sub StoreOnDropbox()
Dim oDBox As New CloudStorage
Dim oDBoxConfig As AppLimit.CloudComputing.SharpBox.ICloudStorageConfiguration = CloudStorage.GetCloudConfigurationEasy(nSupportedCloudConfigurations.DropBox)
Dim oAccessToken As ICloudStorageAccessToken = Nothing
Using fs As IO.FileStream = File.Open("C:\Users\davidd5\Desktop\token.txt", FileMode.Open, FileAccess.Read, FileShare.None)
oAccessToken = oDBox.DeserializeSecurityToken(fs)
End Using
Dim oStorageToken = oDBox.Open(oDBoxConfig, oAccessToken)
Dim srcFile = Environment.ExpandEnvironmentVariables("C:\Users\davidd5\Desktop\token.txt")
Dim publicFolder = oDBox.GetFolder("/Public")
oDBox.UploadFile(srcFile, publicFolder)
oDBox.Close()
End Sub
The error occurs on the GetFolder function. I have tagged both vb.net and C# as the documentation is in C# and I've translated it to vb.net.
After reading about then posting about the same error in the link provided by IanBailey, I changed:
var publicFolder = dropBoxStorage.GetFolder("/Public");
to
var publicFolder = dropBoxStorage.GetRoot();
The file then uploaded successfully.
EDIT: However, I just realised that you cannot share files within the apps folder (that GetRoot points to), so therefore the problem is still occurring for me.
EDIT 2: I think the problem is due to permissions when creating your app on dropbox. When you first create the app, there is the option to grant access to either the "Apps" folder, or the entire users' dropbox. I was getting the error then I created a new app that requested access to the entire users' dropbox and was then able to get at the public folder.
The problem is due to permissions when creating your app on dropbox. When you first create the app, there is the option to grant access to either the "Apps" folder, or the entire users' dropbox. I was getting the error until I created a new app that requested access to the entire users' dropbox and was then able to get at the public folder.

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.

File Access Denied

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

Categories