在我的MVC网站上,有一个归档旧文件并写入新文件的页面。
但是,当我存档旧文件时,出现以下错误:
System.UnauthorizedAccessException was caught HResult=-2147024891 Message=Access to the path is denied. Source=mscorlib StackTrace: at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) at System.IO.__Error.WinIOError() at System.IO.File.InternalMove(String sourceFileName, String destFileName, Boolean checkHost) at System.IO.File.Move(String sourceFileName, String destFileName) at Controller.Action in C:\Program\Controllers\MyController.cs:line 201 InnerException:
我已经检查了我正在模拟的帐户的权限,并且该帐户对我要写入的文件夹具有修改,读取和执行,列出文件夹内容,读取和写入权限。
也许我错过了关于文件权限的东西? 错误是当我试图将文件移动到\ server123 \ D $ \ Archive上的存档时。 我知道,当我在C:\ Temp \ Archive(我的机器)上存档文件时,程序完美地工作。 我也可以写一个新的文件没有任何麻烦\ server123 \testing。 错误是因为我正在从服务器的一个驱动器移动到另一个? 如果是这样的话…有没有办法绕过它,所以我可以从\ server123 \ Test写入\ server123 \ D $ \ Archive?
这是我用来移动文件的代码。
[AcceptVerbs(HttpVerbs.Post)] public ActionResult MoveFile(MoveFileViewModel model) { string cartonsXml = GetCartonsXml(model); try { //Impersonate user who has access to both folders. string user = ConfigurationManager.AppSettings["FileUser"].ToString(); string domain = ConfigurationManager.AppSettings["FileDomain"].ToString(); string password = ConfigurationManager.AppSettings["FilePassword"].ToString(); ImpersonateUser impersonateUser = new ImpersonateUser(); IntPtr token = impersonateUser.GetUserToken(user, domain, password); if (token != IntPtr.Zero) { using (WindowsImpersonationContext wic = WindowsIdentity.Impersonate(token)) { //Move old cartons.xml file to archive. string oldCartonsFilePath = Path.Combine(@"\\server123\Test", "cartons.xml"); string archiveFilePath = Path.Combine(@"\\server123\D$\Archive", "cartons(" + DateTime.Now.Month + "-" + DateTime.Now.Day + "-" + DateTime.Now.Year + ")." + Guid.NewGuid().ToString() + ".xml"); System.IO.File.Move(oldCartonsFilePath, archiveFilePath); //This is where I catch the exception! //Write new cartons.xml file. string newCartonsFilePath = Path.Combine(@"\\server123\Test", "cartons.xml"); using (StreamWriter sw = new StreamWriter(newCartonsFilePath)) { sw.WriteLine(cartonsXml); sw.Close(); } ViewBag.MsgText = "Complete!"; ViewBag.MsgColor = "Green"; } } else { ViewBag.MsgText = "Credentials failed! Files not moved!"; ViewBag.MsgColor = "Red"; } } catch (Exception ex) { ViewBag.MsgText = ex.Message; ViewBag.MsgColor = "Red"; } return View(model); }
请帮忙! 🙁
经过各种试验和错误之后,我创建了一个我试图访问的文件夹的共享,授予我正在使用的读/写权限的帐户,现在代码正常工作。 我将根据我在这里看到的评论更新我的代码。 多谢你们!