File.Exists 从网络共享返回 false

发布于 2024-07-10 05:15:44 字数 292 浏览 5 评论 0原文

我一直在开发一个 ASP.NET 项目,该项目将把上传的文件保存到网络共享。 我想我可以只使用虚拟目录就可以了,但我一直在努力解决 Directory.CreateDirectory 的权限问题。

我能够上传文件,因此我决定更改代码以将所有内容放在一个目录中,但这需要我使用 File.Exists 以避免覆盖重复项。

现在我已经更新了所有代码,我发现无论我做什么,当我针对网络共享进行测试时,File.Exists 总是返回 false(文件肯定存在)。

有任何想法吗? 我对网络共享已经束手无策了。

I've been working on a ASP.NET project that is going to save uploaded files to a network share. I figured I could just use a virtual directory and be fine, but I have been struggling with permissions for Directory.CreateDirectory.

I was able to upload files so I decided to change my code to place everything in a single directory, however this requires me to make use of File.Exists to avoid overwriting duplicates.

Now that I have all my code updated, I have discovered that no matter what I do, File.Exists always returns false (The file definitely exists) when I test against the network share.

Any ideas? I'm coming to the very end of my rope with network shares.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

终陌 2024-07-17 05:15:44

File.Exist 实际上并不检查文件是否存在。 相反,它会检查您具有一定访问权限的文件是否存在。 如果您知道该文件存在,则可能的问题是您无权访问它。

File.Exist doesn't actually check for existance of a file. It instead checks for Existance of files that you have some measure of access to. If you know the file exists, the likely problem is that you don't have access to it.

知足的幸福 2024-07-17 05:15:44

我最近刚刚从事一个非常类似的项目,我将文件保存到网络共享。 两台计算机位于同一子网中,但不受域控制器控制,因此每台计算机都有自己的用户。

我在两台计算机上创建了一个具有相同用户名和密码的用户。 然后我创建了一个网络共享并设置文件夹/共享权限以允许用户读写。

然后,我创建了以下类来管理模拟:

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

I just recently worked on a very similar project where I am saving files to a network share. The two computers are on the same subnet, but are not controlled by domain controller, so each computer has it's own users.

I created a user with the same username and password on both computers. Then I created a network share and set the folder/share permissions to allow read-write for the user.

I then created the following class to manage the impersonation:

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

Then in the ASP.NET page I did the following:

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();
七色彩虹 2024-07-17 05:15:44

也许您正在运行的代码(即 ASP.NET 服务器代码)正在作为无权访问该网络共享的用户(例如 IIS 用户)运行。

我认为 IIS 不应该作为高权限用户运行,默认情况下该用户有权查看其他计算机上的共享。

Perhaps your code which is running (i.e. ASP.NET server code) is running as a user (e.g. the IIS user) which doesn't have permission to access that network share.

I think that IIS isn't supposed to be run as a highly-priviledged user, which by default has permission to view shares on other machines.

全部不再 2024-07-17 05:15:44

我使用了几乎相同的代码,但让我的类实现了 IDisposable 接口,并将 Undo() 添加到了 Dispose() 方法中。 如果您是唯一使用它的开发人员并且您总是以正确的方式做事,那么此代码可以正常工作,对吧?

I used much the same code, but had my class implement the IDisposable interface, and added the Undo() to the Dispose() method. This code works fine, if you're the only developer using it and you'll always do things the right way, right?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文