删除文件抛出异常UnauthorizedAccessException?

时间:2013-12-25 01:49:12

标签: c#

我在复制文件后尝试删除文件,但我有这个例外

System.UnauthorizedAccessException was unhandled
  HResult=-2147024891
  Message=Access to the path 'C:\Users\---\Downloads\file.zip' is denied.
  Source=mscorlib
  StackTrace:
       at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
       at System.IO.File.InternalDelete(String path, Boolean checkHost)
       at CleanDownloadFolder.Program.CopyDirectory(String sourcePath, String targetPath) in c:\Users\Abdalla\Documents\Visual Studio 2012\Projects\CleanDownloadFolder\CleanDownloadFolder\Program.cs:line 48
       at CleanDownloadFolder.Program.Main(String[] args) in c:\Users\Abdalla\Documents\Visual Studio 2012\Projects\CleanDownloadFolder\CleanDownloadFolder\Program.cs:line 16
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: 


C# code
     if (Path.GetExtension(fileName) == ".zip")
                        {
                            System.IO.File.Copy(s, destFile, true);
                            System.IO.File.Delete(s);
                        }

2 个答案:

答案 0 :(得分:0)

如果您已启用UAC并且未以"Administrator"运行应用程序,则通常无法从系统驱动器中删除。

您是否尝试将文件复制到其他位置(like D:)并删除

你也可能会发现这个有趣的

How does Read-Only affect a Directory when using C#/.Net?

答案 1 :(得分:0)

引发错误是因为您的应用程序没有足够的权限来删除Downloads处的文件。你可以:

  1. 使用System.Diagnostics.Process命名空间在管理员下生成您自己的新进程。有关详细信息,请click here
  2. 将您的文件下载到您有权删除任何文件的另一个目录,例如AppData目录。
  3. 您可以使用Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)获取AppData的路径,然后为您的应用程序创建一个目录。