파일. 네트워크 공유에서 False를 반환합니다
-
03-07-2019 - |
문제
업로드 된 파일을 네트워크 공유에 저장하는 ASP.NET 프로젝트를 진행하고 있습니다. 나는 가상 디렉토리를 사용하고 괜찮을 수 있다고 생각했지만 Directory.createdirectory에 대한 권한으로 어려움을 겪고 있습니다.
파일을 업로드 할 수 있으므로 모든 내용을 단일 디렉토리에 배치하기 위해 코드를 변경하기로 결정했지만,이를 통해 복사를 피하기 위해 File.Exists를 사용해야합니다.
이제 모든 코드를 업데이트 했으므로 네트워크 공유에 대해 테스트 할 때 File.exists가 항상 False (파일이 확실히 존재 함)를 반환한다는 것을 알게되었습니다.
어떤 아이디어? 네트워크 공유로 밧줄의 끝에오고 있습니다.
해결책
나는 최근에 파일을 네트워크 공유에 저장하는 매우 유사한 프로젝트에서 작업했습니다. 두 컴퓨터는 동일한 서브넷에 있지만 도메인 컨트롤러에 의해 제어되지 않으므로 각 컴퓨터에는 자체 사용자가 있습니다.
두 컴퓨터에서 동일한 사용자 이름과 비밀번호를 가진 사용자를 만들었습니다. 그런 다음 네트워크 공유를 생성하고 폴더/공유 권한을 설정하여 사용자에 대한 읽기 제기를 허용합니다.
그런 다음 가장을 관리하기 위해 다음 수업을 만들었습니다.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Security.Permissions;
using System.Text;
namespace MyProject.Business.Web
{
public class SecurityManager
{
#region DLL Imports
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public extern static bool CloseHandle(IntPtr handle);
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public extern static bool DuplicateToken(IntPtr ExistingTokenHandle, int SECURITY_IMPERSONATION_LEVEL, ref IntPtr DuplicateTokenHandle);
#endregion
public string Domain { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
private WindowsImpersonationContext m_CurrentImpersonationContext;
[PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")]
public void StartImpersonation()
{
const int LOGON32_PROVIDER_DEFAULT = 0;
const int LOGON32_LOGON_INTERACTIVE = 2;
IntPtr tokenHandle = IntPtr.Zero;
IntPtr dupeTokenHandle = IntPtr.Zero;
// obtain a handle to an access token
bool wasLogonSuccessful = LogonUser(UserName, Domain, Password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref tokenHandle);
if (!wasLogonSuccessful)
throw new Exception(String.Format("Logon failed with error number {0}", Marshal.GetLastWin32Error()));
// use the token handle to impersonate the user
WindowsIdentity newId = new WindowsIdentity(tokenHandle);
m_CurrentImpersonationContext = newId.Impersonate();
// free the tokens
if (tokenHandle != IntPtr.Zero)
CloseHandle(tokenHandle);
}
public void EndImpersonation()
{
m_CurrentImpersonationContext.Undo();
}
}
}
그런 다음 ASP.NET 페이지에서 다음을 수행했습니다.
SecurityManager sm = new SecurityManager();
sm.UserName = ConfigurationManager.AppSettings["UserFileShareUsername"];
sm.Password = ConfigurationManager.AppSettings["UserFileSharePassword"];
sm.StartImpersonation();
if (!Directory.Exists(folderPath)) Directory.CreateDirectory(folderPath);
File.Move(sourcePath, destinationPath);
sm.EndImpersonation();
다른 팁
file.exist는 실제로 파일의 존재를 확인하지 않습니다. 대신 액세스 측정이있는 파일의 존재를 확인합니다. 파일이 존재한다는 것을 알고 있다면 파일에 액세스 할 수 없다는 것입니다.
실행중인 코드 (예 : ASP.NET 서버 코드)는 해당 네트워크 공유에 액세스 할 수있는 권한이없는 사용자 (예 : IIS 사용자)로 실행 중입니다.
IIS는 기본적으로 다른 시스템에서 주식을 볼 수있는 권한이있는 고도로 비판적인 사용자로 실행되어서는 안된다고 생각합니다.
나는 동일한 코드를 거의 사용했지만 내 클래스가 idisposable 인터페이스를 구현하고 undo ()를 dispose () 메소드에 추가했습니다. 이 코드는 잘 작동합니다. 만약 당신이 그것을 사용하는 유일한 개발자라면 항상 올바른 방식으로 일을 할 것입니다.