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
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 .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.