C#以文件夹共享方式实现2G以上大文件传输

protected void Page_Load(object sender, EventArgs e)
{
    //下面的方法调用时最好做成异步线程,以免在文件过大时让用户主线程等待过久

    //如果asp.net模拟域账号访问客户端共享文件夹,报对路径"\\xxx\folder"的访问被拒绝
    //需在web.config文件system.web节配置<identity impersonate="true" userName="域\域账号" password="密码" />
    IntPtr ptr = default(IntPtr);
    if (WinLogonHelper.LogonUser("域账号", "域", "密码", 9, 0, ref ptr) != 0)
    {
        using (WindowsIdentity wi = new WindowsIdentity(ptr))
        {
            using (WindowsImpersonationContext wic = wi.Impersonate())
            {
                if (!Directory.Exists(@"\\\\path\\folder"))
                {
                    //客户端文件夹对当前域账号开放共享,此处域账号可以根据所开放的权限对文件夹进行访问,例如读取文件夹中的文件、将文件copy到其他地方
                    //......(共享文件夹的方式可以传输2G以上的多个文件)

                    //将文件从客户端复制到服务端后,可以对新生成的文件目录设置共享访问权限,例如设置只读权限
                    SetFolderACL("文件保存物理路径或网络地址", "域\\(一个反斜杠)域账号", FileSystemRights.Read, AccessControlType.Allow);
                }
            }
        }
    }
}

public static class WinLogonHelper
{
    [DllImport("advapi32.DLL", SetLastError = true)]
    public static extern int LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);
}

public static bool SetFolderACL(String folderPath, String userName, FileSystemRights rights, AccessControlType allowOrDeny)
{
    bool modified;

    DirectoryInfo folder = new DirectoryInfo(folderPath);
    DirectorySecurity fs1 = folder.GetAccessControl(AccessControlSections.All);
    InheritanceFlags inherits = InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit;
    FileSystemAccessRule accRule = new FileSystemAccessRule(userName, rights, inherits, PropagationFlags.None, allowOrDeny);
    fs1.ModifyAccessRule(AccessControlModification.Add, accRule, out modified);
    folder.SetAccessControl(fs1);

    DirectorySecurity fs2 = Directory.GetAccessControl(folderPath);
    fs2.SetAccessRuleProtection(false, true);
    Directory.SetAccessControl(folderPath, fs2);

    return modified;
}

如果采用用户在浏览器网页端提交文件表单方式上传,那么文件传输大小会受到三个方面的限制:浏览器所在机器内存大小、Web服务器允许传输的最大文件大小、程序本身接收文件的对象所能承载的文件大小。IIS只允许传输大小在2G以内的文件,Asp.Net在接收文件的对象中使用的是int类型的属性来标识文件所占字节数,因此文件大小也不能大于2G。而上面拷贝文件的过程使用的是FileInfo类型对象的CopyTo()方法,FileInfo类型对象使用long类型的属性来标识文件所占字节数,long类型的最大值可以标识几百万G的文件,因而对于单个文件来说传输大小几乎没有限制。

posted @ 2017-05-22 15:48  Arlar  阅读(768)  评论(0编辑  收藏  举报