从文件夹中删除文件抛出错误

问题描述:

我有一个文件夹G:\图像,它允许我通过c#从上传页面插入图像,当我从文件夹中删除图像时出现问题我收到以下错误。从文件夹中删除文件抛出错误

System.IO .__ Error.WinIOError(的Int32的errorCode,字符串maybeFullPath)
在System.IO.File.InternalDelete(字符串路径,布尔checkHost)

如果用户想要更新自己的他们上传图片,然后检查数据库中的旧图片,然后使用下面的代码将其从文件夹中删除,然后添加新的图片ID。

但是,如果我上传新图像,然后错误发生后再次上传图像。

我的代码是

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())); 
    } 
} 

-----------------------按照要求改变e.tostring() - - - - -----------

错误是:System.UnauthorizedAccessException:对路径 'G:\图片\ 5bb188f0-2508-4cbd-b83d-9a5fe5914a1b.png' 被拒绝。在 System.IO .__ Error.WinIOError(的Int32的errorCode,字符串maybeFullPath)
在System.IO.File.InternalDelete(字符串路径,布尔checkHost)

但如上所述,我可以插入,删除,但如果我插入,发生错误后直接删除。

+5

日志'e.ToString()'让.NET告诉你什么是错的 – Alex 2014-09-12 13:26:59

+3

或者更好的是:**不要捕获任何异常都** – 2014-09-12 13:27:26

+0

如果你有要使用它,以便您可以看到错误,请尝试记录e.Message和e.StackTrace。 – Silvestre 2014-09-12 13:30:20

试试这个:

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

抱歉没有工作 – 2014-09-12 14:42:44