/// <summary> /// Zip压缩至byte[] /// </summary> /// <param name="srcFolder"></param> /// <param name="最顶层是否是文件夹(如果不是,则是文件夹下的一个个文件)"></param> /// <returns></returns> public static byte[] CompressFromFolder(string srcFolder, bool topFolder) { AbstractFile memoryFile = new MemoryFile(); //AbstractFile memoryFile = new DiskFile(System.IO.Path.GetTempFileName()); ZipArchive archive = CreateZipArchive(memoryFile); if (topFolder) { AbstractFolder source = new DiskFolder(srcFolder); source.CopyTo(archive, true); } else { foreach (var i in archive.GetItems(false)) { i.CopyTo(archive, true); } } byte[] buffer; using (Stream destStream = memoryFile.OpenRead(FileShare.Read)) { buffer = new byte[destStream.Length]; destStream.Read(buffer, 0, buffer.Length); destStream.Close(); } memoryFile.Delete(); return(buffer); }
public IActionResult Get(int keySizeInBits) { byte[] privateKeyBytes; byte[] publicKeyBytes; byte[] rsaPublicPKCS1Bytes; var keygen = new SshKeyGenerator.SshKeyGenerator(keySizeInBits); string privateKey = keygen.ToPrivateKey(); string publicKey = keygen.ToPublicKey(); string sshPubKey = keygen.ToRfcPublicKey(); privateKeyBytes = Encoding.Default.GetBytes(privateKey); publicKeyBytes = Encoding.Default.GetBytes(publicKey); rsaPublicPKCS1Bytes = Encoding.Default.GetBytes(sshPubKey); MemoryFile mfPriv = new MemoryFile($"{KEYTYPE}-{keySizeInBits}bits-private-key.pem", privateKeyBytes); MemoryFile mfPublic = new MemoryFile($"{KEYTYPE}-{keySizeInBits}bits-public-key.pem", publicKeyBytes); MemoryFile mfRSAPublicPKCS1Bytes = new MemoryFile($"{KEYTYPE}-{keySizeInBits}bits-public-ssh-key.pem", rsaPublicPKCS1Bytes); byte[] zipBytes = ZipMemoryFile.ZipItAllFromAndToMemory(CompressionLevel.Optimal, mfPriv, mfPublic, mfRSAPublicPKCS1Bytes); var result = new FileContentResult(zipBytes, "application/zip") { FileDownloadName = $"RSA-keypair-{keySizeInBits}bits.zip" }; return(result); }
static void TestArray() { var count = 10_000_000L; using (var mmf = new MemoryFile("list.db")) { var sw = Stopwatch.StartNew(); var arr = new MemoryArray <Int64>(mmf, count); for (var i = 0; i < count; i++) { arr[i] = i; } sw.Stop(); var ms = sw.ElapsedMilliseconds; Console.WriteLine("赋值[{0:n0}] {1:n0}tps", count, count * 1000L / ms); sw.Restart(); for (var i = 0; i < count; i++) { var n = arr[i]; } sw.Stop(); ms = sw.ElapsedMilliseconds; Console.WriteLine("取值[{0:n0}] {1:n0}tps", count, count * 1000L / ms); } }
public void WriteAndReadDoublesViaMemoryFile() { var file = new MemoryFile("rwb"); Assert.NotNull(file); Assert.True(file.CanWrite); var data0 = new double[4]; for (var i = 0; i < data0.Length; ++i) { data0[i] = (double)i; } file.WriteDoubles(data0); Assert.Equal(data0.Length * sizeof(double), file.Position); file.Seek(0); var data1 = new double[data0.Length]; var rd = file.ReadDoubles(data1, data0.Length); Assert.Equal(rd, data0.Length); Assert.Equal(data0.Length * sizeof(double), file.Position); for (var i = 0; i < rd; ++i) { Assert.Equal(data0[i], data1[i]); } file.Close(); Assert.False(file.IsOpen); }
public void IsExpectedErrors(MemoryFile file) { var importFile = Imports.Imports.ImportTest1(file); Assert.AreEqual(importFile.Errors.Count, 19); Assert.AreEqual("Error in line 5, column 3 (Col3Int): Incorrect value ('-1'). Value has to be between 0 and 2147483647.", importFile.Errors[0]); Assert.AreEqual("Error in line 5, column 11 (Col11Email): Incorrect value ('ABC'). Does not meet the pattern 'Email'.", importFile.Errors[1]); Assert.AreEqual("Error in line 6, column 2 (Col2StringNull): Incorrect value ('Red 1234', length: 8). Max lenght 5.", importFile.Errors[2]); Assert.AreEqual("Error in line 6, column 3 (Col3Int): Value is required.", importFile.Errors[3]); Assert.AreEqual("Error in line 6, column 5 (Col5DateTime): Value is required.", importFile.Errors[4]); Assert.AreEqual("Error in line 6, column 8 (Col8DecimalNull): Cannot convert 'test' to System.Decimal.", importFile.Errors[5]); Assert.AreEqual("Error in line 6, column 9 (Col9Bool): Cannot convert 'test1' to System.Boolean.", importFile.Errors[6]); Assert.AreEqual("Error in line 6, column 11 (Col11Email): Incorrect value ('test.@gmail'). Does not meet the pattern 'Email'.", importFile.Errors[7]); Assert.AreEqual("Error in line 6, column 12 (Col12CustomRegex): Incorrect value ('ABC'). Does not meet the pattern 'Custom'.", importFile.Errors[8]); Assert.AreEqual("Error in line 7, column 6 (Col6DateTimeNull): Cannot convert '36892' to System.DateTime.", importFile.Errors[9]); Assert.AreEqual("Error in line 7, column 7 (Col7Decimal): Cannot convert 'CDF' to System.Decimal.", importFile.Errors[10]); Assert.AreEqual("Error in line 7, column 11 (Col11Email): Incorrect value ('test.gmail.com'). Does not meet the pattern 'Email'.", importFile.Errors[11]); Assert.AreEqual("Error in line 8, column 4 (Col4IntNull): Incorrect value ('-100'). Value has to be between -90 and 90.", importFile.Errors[12]); Assert.AreEqual("Error in line 8, column 7 (Col7Decimal): Incorrect value ('11.2'). Value has to be between 0 and 10.", importFile.Errors[13]); Assert.AreEqual("Error in line 8, column 11 (Col11Email): Value is required.", importFile.Errors[14]); Assert.AreEqual("Error in line 9, column 1 (Col1String): Value is required.", importFile.Errors[15]); Assert.AreEqual("Error in line 9, column 8 (Col8DecimalNull): Incorrect value ('130.0'). Value has to be between 0 and 100.", importFile.Errors[16]); Assert.AreEqual("Error in line 9, column 12 (Col12CustomRegex): Value is required.", importFile.Errors[17]); Assert.AreEqual("Error in line 10, column 3 (Col3Int): Cannot convert 'QWE' to System.Int32.", importFile.Errors[18]); }
public void TestConcurrentWrite() { MemoryFile file = new MemoryFile(); // SetLength() using (var s = file.Open(FileAccess.ReadWrite, FileShare.None)) { // Write "HelloWorld" with 10000 tasks concurrently. Parallel.For(0, 10000, (int x) => s.Write(HelloWorld)); s.Position = 0L; byte[] data = new byte[HelloWorld.Length]; for (int i = 0; i < 10000; i++) { int c = s.Read(data, 0, data.Length); Assert.AreEqual(c, data.Length); for (int j = 0; j < data.Length; j++) { Assert.AreEqual(data[j], HelloWorld[j]); } } Assert.AreEqual(-1, s.ReadByte()); // Check position Assert.AreEqual(HelloWorld_x10000.Length, s.Position); Assert.AreEqual(HelloWorld_x10000.Length, file.Length); } }
public void WriteAndReadStorageDoublesViaMemoryFile() { const int size = 10; var file = new MemoryFile("rwb"); Assert.NotNull(file); Assert.True(file.CanWrite); var storage0 = new DoubleTensor.DoubleStorage(size); for (var i = 0; i < size; ++i) { storage0[i] = (double)i; } file.WriteDoubles(storage0); Assert.Equal(size * sizeof(double), file.Position); file.Seek(0); var storage1 = new DoubleTensor.DoubleStorage(size); var rd = file.ReadDoubles(storage1); Assert.Equal(rd, size); Assert.Equal(size * sizeof(double), file.Position); for (var i = 0; i < rd; ++i) { Assert.Equal(storage0[i], storage1[i]); } file.Close(); Assert.False(file.IsOpen); }
public void TestConcurrentRead() { MemoryFile file = new MemoryFile(); // Write data using (var s = file.Open(FileAccess.Write, FileShare.None)) s.Write(HelloWorld_x10000); // Read data with 100 tasks concurrently Parallel.For(0, 100, (int x) => { using (var s = file.Open(FileAccess.Read, FileShare.Read)) { byte[] data = new byte[HelloWorld.Length]; for (int i = 0; i < 10000; i++) { int c = s.Read(data, 0, data.Length); Assert.AreEqual(c, data.Length); for (int j = 0; j < data.Length; j++) { Assert.AreEqual(data[j], HelloWorld[j]); } } Assert.AreEqual(-1, s.ReadByte()); } }); }
public void WriteAndReadDoubleTensorViaMemoryFile() { const int size = 10; var file = new MemoryFile("rwb"); Assert.NotNull(file); Assert.True(file.CanWrite); var tensor0 = new DoubleTensor(size); for (var i = 0; i < size; ++i) { tensor0[i] = (double)i; } file.WriteTensor(tensor0); Assert.Equal(size * sizeof(double), file.Position); file.Seek(0); var tensor1 = new DoubleTensor(size); var rd = file.ReadTensor(tensor1); Assert.Equal(rd, size); Assert.Equal(size * sizeof(double), file.Position); for (var i = 0; i < rd; ++i) { Assert.Equal(tensor1[i], tensor1[i]); } file.Close(); Assert.False(file.IsOpen); }
public void TestObserve() { MemoryFile file = new MemoryFile(); Observer observer = new Observer(); IDisposable disposable = file.Subscribe(observer); using (Stream s = file.Open(FileAccess.ReadWrite, FileShare.None)) { byte[] data = HelloWorld_x100; s.Write(data, 0, data.Length); Assert.AreEqual(data.Length, s.Position); Assert.AreEqual(data.Length, s.Length); Assert.AreEqual(1, observer.events.Count); Assert.AreSame(file, observer.events[0].File); Thread.Sleep(1500); s.SetLength(100L); Assert.AreEqual(2, observer.events.Count); Assert.AreSame(file, observer.events[1].File); Assert.AreEqual(s.Length, 100L); Assert.AreEqual(file.Length, 100L); } Assert.IsFalse(observer.closed); disposable.Dispose(); Assert.IsTrue(observer.closed); }
static void Main(string[] args) { const string str = @"#first comment some: element #inline comment #another comment other: element #in #le comment"; var file = new MemoryFile(str); var s = new PENIS(file); Console.WriteLine(file.Content); s.Set("other", "i don't know"); s.Save(); Console.WriteLine("============================="); Console.WriteLine(file.Content); s.Remove("some"); s.Save(); Console.WriteLine("============================="); Console.WriteLine(file.Content); Console.ReadKey(true); }
public void SetBytes() { MemoryFile file = new MemoryFile("testfile.txt"); file.SetFirstByte(42); Assert.Equal(42, file.Bytes[0]); }
public static async System.Threading.Tasks.Task <string> GenerateCloudUrlAsync(this FileViewModel model, ImageService service) { string imageIrl = null; if (model != null && service != null) { try { string strPhoto = (model.Name); string filePath = Path.GetFullPath(model.Name); var test = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); FileStream fs = new FileStream(strPhoto, FileMode.Open, FileAccess.Read); Byte[] imgByte = new byte[fs.Length]; fs.Read(imgByte, 0, System.Convert.ToInt32(fs.Length)); Bitmap originalBMP = new Bitmap(fs); MemoryFile file = new MemoryFile(fs, model.Type, model.Name); fs.Close(); imageIrl = await service.CreateUploadedImageAsync(file, Guid.NewGuid().ToString(), true, 200, 200); } catch (System.Exception ex) { throw ex; } } return(imageIrl); }
public void ProvideIndexer() { MemoryFile file = new MemoryFile("testfile.txt"); file[0] = 42; Assert.Equal(42, file[0]); }
public void ExtensionCanBeParsedCorrectly() { var expected = ".config"; var fileName = "web.Debug.config"; MemoryFile file = new MemoryFile(fileName, null); Assert.Equal(expected, file.Extension); }
/// <summary>Reads the tiles. </summary> private void ReadTiles() { var mapSection = GetSection("IsoMapPack5"); byte[] lzoData = Convert.FromBase64String(mapSection.ConcatenatedValues()); int cells = (FullSize.Width * 2 - 1) * FullSize.Height; int lzoPackSize = cells * 11 + 4; // last 4 bytes contains a lzo pack header saying no more data is left var isoMapPack = new byte[lzoPackSize]; uint totalDecompressSize = Format5.DecodeInto(lzoData, isoMapPack); var mf = new MemoryFile(isoMapPack); int numtiles = 0; for (int i = 0; i < cells; i++) { ushort rx = mf.ReadUInt16(); ushort ry = mf.ReadUInt16(); short tilenum = mf.ReadInt16(); short zero1 = mf.ReadInt16(); ushort subtile = mf.ReadByte(); short z = mf.ReadByte(); byte zero2 = mf.ReadByte(); int dx = rx - ry + FullSize.Width - 1; int dy = rx + ry - FullSize.Width - 1; numtiles++; if (dx >= 0 && dx < 2 * Tiles.Width && dy >= 0 && dy < 2 * Tiles.Height) { var tile = new IsoTile((ushort)dx, (ushort)dy, rx, ry, z, tilenum, subtile); Tiles[(ushort)dx, (ushort)dy / 2] = tile; } } // fix missing tiles // import tiles for (ushort y = 0; y < FullSize.Height; y++) { for (ushort x = 0; x <= FullSize.Width * 2 - 2; x++) { var isoTile = Tiles[x, y]; if (isoTile == null) { // fix null tiles to blank ushort dx = (ushort)(x); ushort dy = (ushort)(y * 2 + x % 2); ushort rx = (ushort)((dx + dy) / 2 + 1); ushort ry = (ushort)(dy - rx + FullSize.Width + 1); Tiles[x, y] = new IsoTile(dx, dy, rx, ry, 0, 0, 0); } } } Logger.Debug("Read {0} tiles", numtiles); }
public void WriteShortToMemoryFile() { var file = new MemoryFile("wb"); Assert.NotNull(file); Assert.True(file.CanWrite); file.Close(); Assert.False(file.IsOpen); }
private MemoryFile GivenWritableTempFile() { _mockIoUtils.Setup(iou => iou.GetTempFileName()).Returns(TestTempFilePath); var newFile = new MemoryFile(); _mockIoUtils.Setup(iou => iou.OpenFile(TestTempFilePath, It.IsAny <FileMode>(), FileAccess.Write)) .Returns(newFile.OpenAppend); return(newFile); }
public Stream CreateFile(FileSystemPath path) { if (!path.IsFile) throw new ArgumentException("The specified path is no file.", "path"); if (!_directories.ContainsKey(path.ParentPath)) throw new DirectoryNotFoundException(); _directories[path.ParentPath].AddLast(path); return new MemoryFileStream(_files[path] = new MemoryFile()); }
public void TestConstructor() { MemoryFile f = new MemoryFile(); Assert.AreEqual(string.Empty, f.Path); Assert.IsFalse(f.HasCopy); Assert.IsNotNull(f.RawCopy); Assert.AreEqual(0, f.RawCopy.Length); }
public void CreateReadWritableMemoryFile() { var file = new MemoryFile("rw"); Assert.NotNull(file); Assert.True(file.CanRead); Assert.True(file.CanWrite); file.Close(); Assert.False(file.IsOpen); }
private void ActionOnFileXlsx(Action <MemoryFile> action) { var fileStream = new FileStream(FilePath, FileMode.Open); using (fileStream) { var file = new MemoryFile(fileStream, ContentType, FileName); action(file); } }
public override async Task <IMessageResponse> PrivateMessage(string userid, byte[] data, string filename) { var file = new MemoryFile { Content = data, FileName = filename }; return(await PrivateMessage(userid, "", file)); }
public override async Task <IMessageResponse> GroupMessage(string groupid, byte[] data, string filename) { var file = new MemoryFile { Content = data, FileName = filename }; return(await GroupMessage(groupid, "", file)); }
public void TestSetLength() { MemoryFile file = new MemoryFile(); // SetLength() using (var s = file.Open(FileAccess.ReadWrite, FileShare.None)) { // Append HelloWorld 10000x s.Write(HelloWorld_x10000); Assert.AreEqual(HelloWorld_x10000.Length, s.Position); Assert.AreEqual(HelloWorld_x10000.Length, s.Length); // SetLength() - Shorten long newLength = 10000L; s.SetLength(newLength); Assert.AreEqual(newLength, s.Position); Assert.AreEqual(newLength, file.Length); s.Position = 0L; for (long i = 0L; i < newLength; i++) { Assert.AreEqual(HelloWorld_x10000[i], s.ReadByte()); } Assert.AreEqual(-1, s.ReadByte()); // SetLength() - Clear s.SetLength(0L); Assert.AreEqual(0L, s.Position); Assert.AreEqual(0L, file.Length); // SetLength() - Grow s.SetLength(newLength); Assert.AreEqual(newLength, file.Length); s.Position = 0L; // Assert all new bytes are zero for (long i = 0L; i < newLength; i++) { Assert.AreEqual(0, s.ReadByte()); } Assert.AreEqual(-1, s.ReadByte()); // SetLength() - Clear, Append, Grow s.SetLength(0L); s.Write(HelloWorld_x10000); long oldLength = s.Length; newLength = s.Length + 10000L; s.SetLength(newLength); // Assert all new bytes are zero s.Position = oldLength; for (int i = 0; i < 10000; i++) { Assert.AreEqual(0, s.ReadByte()); } } }
public void TestSetFile_DoesNotExist() { MemoryFile f = new MemoryFile(); f.Path = "doesnotexist"; f.Refresh(); Assert.IsFalse(f.HasCopy); Assert.IsNotNull(f.RawCopy); Assert.AreEqual(0, f.RawCopy.Length); }
internal StorageObject( MemoryStorageGraph graph, StorageObjectID id ) { this.graph = graph; this.id = id; filedata = new MemoryFile(); filedata.Written += Filedata_Written; }
public void TestSetFile_FileExists() { string path = "TestFile.txt"; MemoryFile f = new MemoryFile(); f.Path = path; f.Refresh(); Assert.IsTrue(f.HasCopy); Assert.AreEqual(path, f.Path); Assert.AreNotEqual(0, f.RawCopy.Length); }
public void CreateAndCleanup() { var file = Path.Combine(_tempFolders.CreateRandomTempFolder(), "CreateAndCleanup.mmf"); using (var mmf = new MemoryFile(file, 100)) { Assert.Equal(100, mmf.FileLength); var spanAll = mmf.GetSpan(); var span40Len10 = mmf.GetSpan(40, 10); var bytes = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; bytes.CopyTo(span40Len10); Assert.Equal(7, spanAll[47]); spanAll[^ 1] = 42;
public Stream CreateFile(FileSystemPath path) { if (!path.IsFile) { throw new ArgumentException("The specified path is no file.", "path"); } if (!_directories.ContainsKey(path.ParentPath)) { throw new DirectoryNotFoundException(); } _directories[path.ParentPath].Add(path); return(new MemoryFileStream(_files[path] = new MemoryFile())); }
public void save_ArgumentException_InvalidDestination_null() { string json = ""; using (StreamReader sr = new StreamReader(@"Resources\test.json")) { json = sr.ReadToEnd(); } HttpPostedFileBase file = new MemoryFile(ToStream(json), "", "test.json"); HttpFileProcessingService.save(file, null); }
public void UploadNewPhoto() { Guid id = Guid.NewGuid(); string filePath = Path.Combine(HttpContext.Current.Server.MapPath("~/Data/Avatars"), Path.GetFileName("test.png")); FileStream fileStream = new FileStream(filePath, FileMode.Open); string fileType = "image/png"; MemoryFile postedFile = new MemoryFile(fileStream, fileType, filePath); _Tests.Storage.UploadAvatar(id, postedFile); filePath = Path.Combine(HttpContext.Current.Server.MapPath("~/Data/Avatars"), Path.GetFileName(id.ToString() + ".png")); FileInfo fileInfo = new FileInfo(filePath); Assert.IsTrue(fileInfo.Exists == true); }
public void UploadNewPhoto() { Guid id = Guid.NewGuid(); string filePath = Path.Combine(Path.Combine(_IudicoPath, @"Data\Avatars"), Path.GetFileName("test.png")); using (FileStream fileStream = new FileStream(filePath, FileMode.Open)) { string fileType = "image/png"; MemoryFile postedFile = new MemoryFile(fileStream, fileType, filePath); _Tests.Storage.UploadAvatar(id, postedFile); } filePath = Path.Combine(Path.Combine(_IudicoPath, @"Data\Avatars"), Path.GetFileName(id + ".png")); FileInfo fileInfo = new FileInfo(filePath); Assert.IsTrue(fileInfo.Exists); }
public void UploadNewPhoto() { var id = Guid.NewGuid(); var filePath = Path.Combine(Path.Combine(this.iudicoPath, @"Data\Avatars"), Path.GetFileName("test.png")); using (var fileStream = new FileStream(filePath, FileMode.Open)) { const string FileType = "image/png"; var postedFile = new MemoryFile(fileStream, FileType, filePath); this.tests.Storage.UploadAvatar(id, postedFile); } filePath = Path.Combine(Path.Combine(this.iudicoPath, @"Data\Avatars"), Path.GetFileName(id + ".png")); var fileInfo = new FileInfo(filePath); Assert.IsTrue(fileInfo.Exists); }
public static void Execute() { var portfolioMediaPath = HttpContext.Current.Server.MapPath("~/media/umbPortFolio"); if (Directory.Exists(portfolioMediaPath) == false || Directory.GetFiles(portfolioMediaPath).Any() == false) return; var mediaService = UmbracoContext.Current.Application.Services.MediaService; var portfolioFolder = mediaService.CreateMedia("UmbPortfolio", -1, Constants.Conventions.MediaTypes.Folder); mediaService.Save(portfolioFolder); foreach (var file in Directory.GetFiles(portfolioMediaPath)) { var fileName = file.Substring(file.LastIndexOf(@"\", StringComparison.Ordinal) + 1); var fileExtension = fileName.Substring(fileName.LastIndexOf(".", StringComparison.Ordinal) + 1); var media = mediaService.CreateMedia(fileName.Replace("." + fileExtension, ""), portfolioFolder, Constants.Conventions.MediaTypes.Image); var uploadFile = new MemoryStream(); using (var fileStream = File.OpenRead(file)) fileStream.CopyTo(uploadFile); var memoryFile = new MemoryFile(uploadFile, MimeTypes.GetMimeType(fileExtension), file); media.SetValue(Constants.Conventions.Media.File, memoryFile); mediaService.Save(media); } var portfolioContentType = UmbracoContext.Current.Application.Services.ContentTypeService.GetAllContentTypes().Single(x => x.Alias == "umbPortfolio"); var contentService = UmbracoContext.Current.Application.Services.ContentService; var portfolios = contentService.GetContentOfContentType(portfolioContentType.Id); foreach (var portfolio in portfolios) { portfolio.SetValue("portfolioMediaFolder", portfolioFolder.Id); contentService.Save(portfolio); } }
public void ReplaceExistingPhoto() { Guid id = Guid.NewGuid(); string filePath = Path.Combine(Path.Combine(_IudicoPath, @"Data\Avatars"), Path.GetFileName("test.png")); string fileType = "image/png"; using (FileStream fileStream = new FileStream(filePath, FileMode.Open)) { MemoryFile postedFile = new MemoryFile(fileStream, fileType, filePath); _Tests.Storage.UploadAvatar(id, postedFile); filePath = Path.Combine(Path.Combine(_IudicoPath, @"Data\Avatars"), Path.GetFileName("test2.png")); } using (FileStream fileStream = new FileStream(filePath, FileMode.Open)) { MemoryFile postedFile = new MemoryFile(fileStream, fileType, filePath); Assert.IsTrue(_Tests.Storage.UploadAvatar(id, postedFile) == 2); } }
/// <summary> /// Zip解压缩byte[]至文件夹 /// </summary> /// <param name="srcByte"></param> /// <param name="destFolder"></param> public static void DecompressToFolder(byte[] srcByte, string destFolder) { AbstractFile memoryFile = new MemoryFile(); //AbstractFile memoryFile = new DiskFile(System.IO.Path.GetTempPath() + "memoryFile.zip"); memoryFile.Create(); using (Stream stream = memoryFile.OpenWrite(true, FileShare.Write)) { stream.Write(srcByte, 0, srcByte.Length); stream.Close(); } // 必须先写MemoryFile再创建ZipArchive ZipArchive archive = CreateZipArchive(memoryFile); AbstractFolder dest = new DiskFolder(destFolder); archive.CopyFilesTo(dest, true, true, null); memoryFile.Delete(); }
public ActionResult MemberRegisterLogic(MemberAddViewModel userModel) { using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork()) { var settings = SettingsService.GetSettings(); var manuallyAuthoriseMembers = settings.ManuallyAuthoriseNewMembers; var memberEmailAuthorisationNeeded = settings.NewMemberEmailConfirmation == true; var homeRedirect = false; var userToSave = new MembershipUser { UserName = _bannedWordService.SanitiseBannedWords(userModel.UserName), Email = userModel.Email, Password = userModel.Password, IsApproved = userModel.IsApproved, Comment = userModel.Comment, }; var createStatus = MembershipService.CreateUser(userToSave); if (createStatus != MembershipCreateStatus.Success) { ModelState.AddModelError(string.Empty, MembershipService.ErrorCodeToString(createStatus)); } else { // See if this is a social login and we have their profile pic if (!string.IsNullOrEmpty(userModel.SocialProfileImageUrl)) { // We have an image url - Need to save it to their profile var image = AppHelpers.GetImageFromExternalUrl(userModel.SocialProfileImageUrl); // Set upload directory - Create if it doesn't exist var uploadFolderPath = HostingEnvironment.MapPath(string.Concat(SiteConstants.Instance.UploadFolderPath, userToSave.Id)); if (uploadFolderPath != null && !Directory.Exists(uploadFolderPath)) { Directory.CreateDirectory(uploadFolderPath); } // Get the file name var fileName = Path.GetFileName(userModel.SocialProfileImageUrl); // Create a HttpPostedFileBase image from the C# Image using (var stream = new MemoryStream()) { // Microsoft doesn't give you a file extension - See if it has a file extension // Get the file extension var fileExtension = Path.GetExtension(fileName); // Fix invalid Illegal charactors var regexSearch = new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars()); var reg = new Regex($"[{Regex.Escape(regexSearch)}]"); fileName = reg.Replace(fileName, ""); if (string.IsNullOrEmpty(fileExtension)) { // no file extension so give it one fileName = string.Concat(fileName, ".jpg"); } image.Save(stream, ImageFormat.Jpeg); stream.Position = 0; HttpPostedFileBase formattedImage = new MemoryFile(stream, "image/jpeg", fileName); // Upload the file var uploadResult = AppHelpers.UploadFile(formattedImage, uploadFolderPath, LocalizationService, true); // Don't throw error if problem saving avatar, just don't save it. if (uploadResult.UploadSuccessful) { userToSave.Avatar = uploadResult.UploadedFileName; } } } // Store access token for social media account in case we want to do anything with it var isSocialLogin = false; if (userModel.LoginType == LoginType.Facebook) { userToSave.FacebookAccessToken = userModel.UserAccessToken; isSocialLogin = true; } if (userModel.LoginType == LoginType.Google) { userToSave.GoogleAccessToken = userModel.UserAccessToken; isSocialLogin = true; } if (userModel.LoginType == LoginType.Microsoft) { userToSave.MicrosoftAccessToken = userModel.UserAccessToken; isSocialLogin = true; } // If this is a social login, and memberEmailAuthorisationNeeded is true then we need to ignore it // and set memberEmailAuthorisationNeeded to false because the email addresses are validated by the social media providers if (isSocialLogin && !manuallyAuthoriseMembers) { memberEmailAuthorisationNeeded = false; userToSave.IsApproved = true; } // Set the view bag message here SetRegisterViewBagMessage(manuallyAuthoriseMembers, memberEmailAuthorisationNeeded, userToSave); if (!manuallyAuthoriseMembers && !memberEmailAuthorisationNeeded) { homeRedirect = true; } try { // Only send the email if the admin is not manually authorising emails or it's pointless SendEmailConfirmationEmail(userToSave); unitOfWork.Commit(); if (homeRedirect) { if (Url.IsLocalUrl(userModel.ReturnUrl) && userModel.ReturnUrl.Length > 1 && userModel.ReturnUrl.StartsWith("/") && !userModel.ReturnUrl.StartsWith("//") && !userModel.ReturnUrl.StartsWith("/\\")) { return Redirect(userModel.ReturnUrl); } return RedirectToAction("Index", "Home", new { area = string.Empty }); } } catch (Exception ex) { unitOfWork.Rollback(); LoggingService.Error(ex); FormsAuthentication.SignOut(); ModelState.AddModelError(string.Empty, LocalizationService.GetResourceString("Errors.GenericMessage")); } } } return View("Register"); }
public void DeleteNotExistingPhoto() { var id = Guid.NewGuid(); var filePath = Path.Combine(Path.Combine(this.iudicoPath, @"Data\Avatars"), Path.GetFileName("test.png")); const string FileType = "image/png"; using (var fileStream = new FileStream(filePath, FileMode.Open)) { var postedFile = new MemoryFile(fileStream, FileType, filePath); this.tests.Storage.UploadAvatar(id, postedFile); this.tests.Storage.DeleteAvatar(id); } Assert.IsTrue(this.tests.Storage.DeleteAvatar(id) == -1); }
public MemoryFileStream(MemoryFile file) { _file = file; }
/// <summary> /// Zip压缩至byte[] /// </summary> /// <param name="srcFolder"></param> /// <param name="最顶层是否是文件夹(如果不是,则是文件夹下的一个个文件)"></param> /// <returns></returns> public static byte[] CompressFromFolder(string srcFolder, bool topFolder) { AbstractFile memoryFile = new MemoryFile(); //AbstractFile memoryFile = new DiskFile(System.IO.Path.GetTempFileName()); ZipArchive archive = CreateZipArchive(memoryFile); if (topFolder) { AbstractFolder source = new DiskFolder(srcFolder); source.CopyTo(archive, true); } else { foreach (var i in archive.GetItems(false)) { i.CopyTo(archive, true); } } byte[] buffer; using (Stream destStream = memoryFile.OpenRead(FileShare.Read)) { buffer = new byte[destStream.Length]; destStream.Read(buffer, 0, buffer.Length); destStream.Close(); } memoryFile.Delete(); return buffer; }
public void DeleteNotExistingPhoto() { Guid id = Guid.NewGuid(); string filePath = Path.Combine(HttpContext.Current.Server.MapPath("~/Data/Avatars"), Path.GetFileName("test.png")); FileStream fileStream = new FileStream(filePath, FileMode.Open); string fileType = "image/png"; MemoryFile postedFile = new MemoryFile(fileStream, fileType, filePath); _Tests.Storage.UploadAvatar(id, postedFile); _Tests.Storage.DeleteAvatar(id); Assert.IsTrue(_Tests.Storage.DeleteAvatar(id) == -1); }