0
votes

I have a folder G:\Images which allows me to insert images from upload page via c#, problem when I go to delete a image from folder I get the following error.

System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.File.InternalDelete(String path, Boolean checkHost)

If a user wants to update their profile picture, they upload the image, I then check the database for old image and then use code below to delete it from folder before adding new image id.

But if I upload new image and then upload image again straight after the error occurs.

My code is

if (System.IO.File.Exists(@"G:\\Images\\" + string.Format("{0}.png", OldProfileImage)))
{
    try
    {
        System.IO.File.Delete(@"G:\\Images\\" + string.Format("{0}.png", OldProfileImage));
    }
    catch(Exception e)
    {
        logger.Error(string.Format("Delete file error Exception is {0} {1}", e.Source.ToString(), e.StackTrace.ToString()));
    }
}

-----------------------As requested changed e.tostring()----------------

Error is: System.UnauthorizedAccessException: Access to the path 'G:\Images\5bb188f0-2508-4cbd-b83d-9a5fe5914a1b.png' is denied. at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.File.InternalDelete(String path, Boolean checkHost)

But as stated above, i can insert, delete, but if i then insert, delete straight after error occurs.

2
log e.ToString() to let .net tell you what's wrongAlex
Or better yet: DO NOT CATCH ANY EXCEPTIONS AT ALL!Uwe Keim
If you have to use it just so you can see the error, try to log e.Message and e.StackTrace.Silvestre
@George, your question needs some cleaning up, you language constructs are very confusing. This sentence makes no sense: "I can add a file then delete it but when I try to add another file straight after the error occurs, but I cannot work out how to close it.". Edit your question an be more precise in describing what is happening.user469104
If you're creating the file, did you correctly clean up whatever you were using to create it (e.g. close/dispose)? If the file is still open for writing to, seems like that could cause some issues.Jeff B

2 Answers

0
votes

I had a similar issue. Mine was a console app. In my local machine, it worked fine, but when i put into server, it gaves me this error on System.IO.File.Delete(file);

To clarify, my account had delete permission. I can manually delete the file.

Later I run the program with the option "Run as admin", and it solved the issue.

-1
votes

Try this:

    string file = @"G:\\Images\\" + string.Format("{0}.png", OldProfileImage);
    System.IO.File.SetAttributes(file, FileAttributes.Normal);
    System.IO.File.Delete(file);