c#连接字符串形式访问微软共享文件夹sharefile

 c#连接字符串形式访问微软共享文件夹sharefile

 public class ShareFileHelper
    {

        private static CloudStorageAccount storageAccount = null;
        private static CloudFileClient fileClient = null;
        private static string filesharebase = "";
        static ShareFileHelper()
        {
            string storageConnectionString = ConfigurationManager.AppSettings["storageconnectionstring"];
            if (!CloudStorageAccount.TryParse(storageConnectionString, out storageAccount))
            {
                throw new Exception("初始化blob fileshare异常");
            }
            fileClient = storageAccount.CreateCloudFileClient();
            var url = fileClient.BaseUri.ToString();
            if (url.LastIndexOf("/").Equals(url.Length - 1))
            {
                url = url.Substring(0, url.Length - 1);
            }
            filesharebase = url;
        }
        /// <summary>
        /// 初始化share
        /// </summary>
        /// <param name="shareName"></param>
        public static void CreateShare(string shareName)
        {
            CloudFileShare share = fileClient.GetShareReference(shareName);
            share.CreateIfNotExists();
        }
        /// <summary>
        /// 上传本地文件到blobfileshare
        /// </summary>
        /// <param name="localPath">本地路径</param>
        /// <param name="toPath">blob路径</param>
        public static void UploadFileToBlobFileShare(string localPath, string toPath)
        {
            UploadFile(toPath, localPath: localPath);
        }
        /// <summary>
        /// 上传文件流到blob
        /// </summary>
        /// <param name="stream"></param>
        /// <param name="streamLength"></param>
        /// <param name="toPath"></param>
        public static void UploadStreamToBlobFileShare(Stream stream, int streamLength, string toPath)
        {
            UploadFile(toPath, 2, stream: stream, streamLength: streamLength);
        }
        /// <summary>
        /// 上传文件到blob 1物理路径上传 2文件流上传
        /// </summary>
        /// <param name="toPath"></param>
        /// <param name="uploadType"></param>
        /// <param name="localPath">本地物理路径</param>
        private static void UploadFile(string toPath, int uploadType = 1, string localPath = "", Stream stream = null, int streamLength = 0)
        {
            var splitArrs = toPath.Split(new string[] { "/", "\\" }, StringSplitOptions.RemoveEmptyEntries);
            CloudFileShare share = null;
            CloudFileDirectory lastCloudFileDir = null;
            for (int i = 0; i < splitArrs.Length; i++)
            {
                if (i == 0)
                {
                    share = fileClient.GetShareReference(splitArrs[i]);
                    if (!share.Exists())
                    {
                        share.CreateAsync();
                    }
                }
                else if (i == 1)
                {
                    CloudFileDirectory signRoot = share.GetRootDirectoryReference();
                    var tempCloudFileDir = signRoot.GetDirectoryReference(splitArrs[i]);
                    if (!tempCloudFileDir.Exists())
                    {
                        tempCloudFileDir.CreateAsync();
                    }
                    lastCloudFileDir = tempCloudFileDir;
                }
                else if (i != splitArrs.Length - 1)
                {
                    var tempCloudFileDir = lastCloudFileDir.GetDirectoryReference(splitArrs[i]);
                    if (!tempCloudFileDir.Exists())
                    {
                        tempCloudFileDir.CreateAsync();
                    }
                    lastCloudFileDir = tempCloudFileDir;
                }
                else
                {
                    CloudFile file = lastCloudFileDir.GetFileReference(splitArrs[i]);
                    if (uploadType == 1)
                    {
                        if (string.IsNullOrEmpty(localPath))
                        {
                            throw new Exception("上传类型为本地文件上传时,物理路径不能为空");
                        }
                        file.UploadFromFileAsync(localPath);
                    }
                    else if (uploadType == 2)
                    {
                        if (stream == null || streamLength == 0)
                        {
                            throw new Exception("上传类型为流上传时,流和长度不能为空");
                        }
                        file.UploadFromStreamAsync(stream, streamLength);
                    }
                }
            }
        }

        /// <summary>
        /// 删除共享中的文件
        /// </summary>
        /// <param name="blodPath">blob路径</param>
        public static void DeleteBlodFile(string blodPath)
        {
            var splitArrs = blodPath.Split(new string[] { "/", "\\" }, StringSplitOptions.RemoveEmptyEntries);
            CloudFileShare share = null;
            CloudFileDirectory lastCloudFileDir = null;
            for (int i = 0; i < splitArrs.Length; i++)
            {
                if (i == 0)
                {
                    share = fileClient.GetShareReference(splitArrs[i]);
                    if (!share.Exists())
                    {
                        return;
                    }
                }
                else if (i == 1)
                {
                    CloudFileDirectory signRoot = share.GetRootDirectoryReference();
                    var tempCloudFileDir = signRoot.GetDirectoryReference(splitArrs[i]);
                    if (!tempCloudFileDir.Exists())
                    {
                        return;
                    }
                    lastCloudFileDir = tempCloudFileDir;
                }
                else if (i != splitArrs.Length - 1)
                {
                    var tempCloudFileDir = lastCloudFileDir.GetDirectoryReference(splitArrs[i]);
                    if (!tempCloudFileDir.Exists())
                    {
                        return;
                    }
                    lastCloudFileDir = tempCloudFileDir;
                }
                else
                {
                    CloudFile file = lastCloudFileDir.GetFileReference(splitArrs[i]);
                    if (file.Exists())
                    {
                        file.Delete();
                    }
                    var list = lastCloudFileDir.ListFilesAndDirectories();
                    if (!list.Any())
                    {
                        lastCloudFileDir.DeleteIfExists();
                    }
                }
            }
        }
        /// <summary>
        /// 资源url地址
        /// </summary>
        /// <param name="shareFilePath"></param>
        /// <returns></returns>
        public static string GetResourceUrlWithSas(string shareFilePath, string sasToken = "")
        {
            if (string.IsNullOrEmpty(sasToken))
            {
                sasToken = GetAccountSASToken();
            }
            return filesharebase + shareFilePath + sasToken;
        }
        /// <summary>
        /// 创建sastoken
        /// </summary>
        /// <param name="storageAccount"></param>
        /// <returns></returns>
        public static string GetAccountSASToken(int expireMonth=3)
        {
            // Create a new access policy for the account.
            SharedAccessAccountPolicy policy = new SharedAccessAccountPolicy()
            {
                SharedAccessStartTime = DateTime.UtcNow,
                Permissions = SharedAccessAccountPermissions.Read,
                //Services = SharedAccessAccountServices.Blob | SharedAccessAccountServices.File,
                Services = SharedAccessAccountServices.File,
                ResourceTypes = SharedAccessAccountResourceTypes.Object,
                SharedAccessExpiryTime = DateTime.UtcNow.AddMonths(expireMonth),
                Protocols = SharedAccessProtocol.HttpsOrHttp
            };
            // Return the SAS token.
            return storageAccount.GetSharedAccessSignature(policy);
        }
    }


版权声明:本文为huang361964533原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。