예제 #1
0
        /// <summary>
        /// Creates a temporary resource for writing content. Split from Commit()
        /// in order to allow concurrent writing of cache entries.
        /// This entry will not be available to cache clients until Commit() is
        /// called passing in the resource returned from this method.
        /// </summary>
        /// <param name="resourceId">Id of the resource.</param>
        /// <param name="debugInfo">Helper object for debugging.</param>
        /// <returns>
        /// The Inserter object with methods to write data, commit or cancel the
        /// insertion.
        /// </returns>
        /// <exception cref="IOException">
        /// On errors during this operation.
        /// </exception>
        public IInserter Insert(string resourceId, object debugInfo)
        {
            // Ensure that the parent directory exists
            StorageFileInfo info   = new StorageFileInfo(new FileType(TEMP_FILE_EXTENSION), resourceId);
            DirectoryInfo   parent = GetSubdirectory(info.ResourceId);

            if (!parent.Exists)
            {
                Mkdirs(parent, "insert");
            }

            try
            {
                FileInfo file = info.CreateTempFile(parent);
                return(new InserterImpl(this, resourceId, file));
            }
            catch (IOException)
            {
                _cacheErrorLogger.LogError(
                    CacheErrorCategory.WRITE_CREATE_TEMPFILE,
                    typeof(DefaultDiskStorage),
                    "insert");

                throw;
            }
        }
예제 #2
0
 public static void AssertValidStorageFileInfo(StorageFileInfo storageFileInfo)
 {
     Assert.IsNotNull(storageFileInfo.ETag);
     Assert.IsNotNull(storageFileInfo.LastModified);
     Assert.IsNotNull(storageFileInfo.IsServerEncrypted);
     Assert.IsNotNull(storageFileInfo.SmbProperties);
     AssertValidFileSmbProperties(storageFileInfo.SmbProperties);
 }
예제 #3
0
        private string GetFilename(string resourceId)
        {
            StorageFileInfo fileInfo = new StorageFileInfo(
                new FileType(CONTENT_FILE_EXTENSION), resourceId);

            string path = GetSubdirectoryPath(fileInfo.ResourceId);

            return(fileInfo.ToPath(path));
        }
예제 #4
0
            public void VisitFile(FileSystemInfo file)
            {
                StorageFileInfo info = _parent.GetShardFileInfo(file);

                if (info != null && info.Type.Value == FileType.CONTENT)
                {
                    result.Add(new EntryImpl(info.ResourceId, (FileInfo)file));
                }
            }
예제 #5
0
            public override Stream GetStream(HttpContent parent, HttpContentHeaders headers)
            {
                if (parent == null)
                {
                    throw new ArgumentNullException("parent");
                }

                if (headers == null)
                {
                    throw new ArgumentNullException("headers");
                }

                if (string.IsNullOrEmpty(headers.ContentDisposition.FileName))
                {
                    _isFormData.Add(true);
                    return(new MemoryStream());
                }

                var contentType = headers.ContentType == null ? string.Empty : headers.ContentType.MediaType;

                if (string.IsNullOrWhiteSpace(contentType))
                {
                    contentType = System.Web.MimeMapping.GetMimeMapping(headers.ContentDisposition.FileName);
                }

                _isFormData.Add(false);

                //创建一个文件信息实体对象
                var fileInfo = new StorageFileInfo(_bucketId)
                {
                    Name = Zongsoft.Common.StringExtension.RemoveCharacters(headers.ContentDisposition.FileName, System.IO.Path.GetInvalidFileNameChars()).Trim('"', '\''),
                    Type = contentType,
                    Size = headers.ContentDisposition.Size.HasValue ? headers.ContentDisposition.Size.Value : -1,
                };

                fileInfo.Path = this.GetFilePath(fileInfo);

                try
                {
                    //将文件信息对象加入到集合中
                    _fileData.Add(fileInfo);

                    if (!FileSystem.Directory.Exists(_bucketPath))
                    {
                        FileSystem.Directory.Create(_bucketPath);
                    }

                    return(FileSystem.File.Open(fileInfo.Path, FileMode.CreateNew, FileAccess.Write));
                }
                catch
                {
                    _fileData.Remove(fileInfo);
                    throw;
                }
            }
예제 #6
0
        /// <summary>
        /// Checks that the file is placed in the correct shard according to its
        /// filename (and hence the represented key). If it's correct its
        /// StorageFileInfo is returned.
        /// </summary>
        /// <param name="file">The file to check.</param>
        /// <returns>
        /// The corresponding FileInfo object if shard is correct, null otherwise.
        /// </returns>
        private StorageFileInfo GetShardFileInfo(FileSystemInfo file)
        {
            StorageFileInfo info = StorageFileInfo.FromFile(file);

            if (info == null)
            {
                return(null); // file with incorrect name/extension
            }

            DirectoryInfo expectedDirectory = GetSubdirectory(info.ResourceId);
            bool          isCorrect         = expectedDirectory.FullName.Equals(file.GetParent().FullName);

            return(isCorrect ? info : null);
        }
예제 #7
0
        /// <summary>
        /// Save the file to locations
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        public string Save(StorageFileInfo file)
        {
            var destFile = GetBaseRelativeFile($"{TEMP}/{file.UploadId.ToString()}{Path.GetExtension(file.FormFile.FileName)}");

            if (!destFile.Directory.Exists)
            {
                destFile.Directory.Create();
            }

            using (var stream = new FileStream(destFile.FullName, FileMode.Create))
                file.FormFile.CopyTo(stream);

            return(GetMD5HashFromFile(destFile.FullName));
        }
        public async Task <StorageFileInfo> ReadFileAsync(string fileAddress)
        {
            using (FileStream fileBytes = new FileStream(fileAddress, FileMode.Open))
            {
                var result = new StorageFileInfo
                {
                    FileName     = Path.GetFileName(fileAddress),
                    DownloadLink = fileAddress
                };

                result.Content = new byte[fileBytes.Length];
                await fileBytes.ReadAsync(result.Content, 0, (int)fileBytes.Length);

                return(result);
            }
        }
예제 #9
0
            private bool IsExpectedFile(FileSystemInfo file)
            {
                StorageFileInfo info = _parent.GetShardFileInfo(file);

                if (info == null)
                {
                    return(false);
                }

                if (info.Type.Value == FileType.TEMP)
                {
                    return(IsRecentFile(file));
                }

                Preconditions.CheckState(info.Type.Value == FileType.CONTENT);
                return(true);
            }
        public async Task <StorageFileInfo> CreateFileAsync(string fileName, byte[] file)
        {
            fileName = this.AdjustPath(fileName);

            using (MemoryStream inputStream = new MemoryStream(file))
            {
                string filePath = fileName;

                // Replace file name with random string
                string pattern        = @"(.*(\/|\\))([\d\w\W]*)\.(.*)";
                string uniqueName     = CryptoService.Instance.RandomString(10);
                string uniqueFileName = Regex.Replace(@fileName, pattern, m => $"{m.Groups[1].Value}{uniqueName}.{m.Groups[4].Value}");
                if (!fileName.Contains(this.outputDirectory))
                {
                    filePath = $@"{outputDirectory}\{uniqueFileName}";
                }

                var directory = Path.GetDirectoryName(filePath);

                if (!Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }

                using (FileStream destinationStream = File.Create(filePath))
                {
                    await inputStream.CopyToAsync(destinationStream);

                    var result = new StorageFileInfo
                    {
                        FileName     = fileName,
                        Location     = filePath,
                        DownloadLink = filePath,
                        Content      = file
                    };

                    return(result);
                }
            }
        }
예제 #11
0
 private string GetFilePath(StorageFileInfo fileInfo)
 {
     //返回当前文件的完整虚拟路径
     return(Zongsoft.IO.Path.Combine(_bucketPath, string.Format("[{0}]{1:n}{2}", fileInfo.BucketId, fileInfo.FileId, System.IO.Path.GetExtension(fileInfo.Name).ToLowerInvariant())));
 }