C# 删除文件引发异常UnauthorizedAccessException?
我试图删除文件后,我复制文件,但我有这个例外C# 删除文件引发异常UnauthorizedAccessException?,c#,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 error
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);
}
如果您启用了
UAC
,并且您不是以“管理员”身份运行应用程序,则您通常无权从系统驱动器中删除
您是否尝试过将文件复制到其他位置(如D:
)并删除
你可能会发现这很有趣
抛出错误是因为您的应用程序没有足够的权限在下载时删除文件。您可以:
使用System.Diagnostics.process
命名空间,在Administrator下生成您自己的新进程。有关详细信息
将您的文件下载到另一个目录,您有权在其中删除任何文件,例如AppData
目录
您可以使用Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
获取AppData的路径,然后为您的应用程序创建一个目录。这对于根目录中的文件是正确的;此文件位于C:\Users\。。。profile dir.您是否尝试以管理员身份运行应用程序?