//should be changed so that file length is programatically determined public void UploadFile(string filename, string hashValue, Stream fileStream) { SessionInfo sessionInfo = SessionManager.Instance.CheckForSession(GetChannelIdentification()); if (sessionInfo == null || sessionInfo.LoggedInUser == null) { throw new InvalidOperationException("Cannot upload files when the user isn't logged in."); } try { using (var context = new DBContext()) { //Determine file size byte[] fileBytes = FileManager.ReadToEnd(fileStream); long fileLength = fileBytes.Length; var fileInfo = new DatabaseInteraction.Models.FileInfo(filename, fileLength, hashValue); //Check if user has leftover space for this file (TODO) if (sessionInfo.LoggedInUser.LeftoverSpace < fileLength) { context.RemoveFile(fileInfo.ID); throw new InvalidOperationException("User doesn't have enough leftover allocated space to upload the desired file."); } else { context.UpdateUserLeftoverSpace(sessionInfo.LoggedInUser.ID, sessionInfo.LoggedInUser.LeftoverSpace - fileLength); } //Add the file record to the database context.TryAddFile(fileInfo, sessionInfo.LoggedInUser); try { if (!FileManager.SaveFile(fileInfo, fileBytes)) { //If file upload fails, revert changes in the database context.RemoveFile(fileInfo.ID); context.UpdateUserLeftoverSpace(sessionInfo.LoggedInUser.ID, sessionInfo.LoggedInUser.LeftoverSpace + fileLength); } } catch (Exception e) { //If file upload fails, revert changes in the database context.RemoveFile(fileInfo.ID); context.UpdateUserLeftoverSpace(sessionInfo.LoggedInUser.ID, sessionInfo.LoggedInUser.LeftoverSpace + fileLength); throw new Exception("File manager error.", e); } } } catch (Exception e) { throw new Exception("Error adding a new file.", e); } }
internal static Stream RetrieveFile(DatabaseInteraction.Models.FileInfo fileInfo) { try { string path = fileInfo.GetFilePath(); var fileName = Path.GetFileName(path); return(File.OpenRead(path)); //byte[] fileBytes = File.ReadAllBytes(path); //return new MemoryStream(fileBytes); } catch (Exception e) { throw new Exception("Error retrieving the file.", e); } }
internal static bool RemoveFile(DatabaseInteraction.Models.FileInfo fileInfo) { try { string path = fileInfo.GetFilePath(); if (File.Exists(path)) { File.Delete(path); } return(true); } catch (Exception) { return(false); } }
internal static bool SaveFile(DatabaseInteraction.Models.FileInfo fileInfo, byte[] fileBytes) { try { string path = fileInfo.GetFilePath(); CreateDirectoryIfNotExists(path); using (var newFileStream = File.Create(path)) { newFileStream.Write(fileBytes, 0, fileBytes.Length); } } catch (Exception) { return(false); } return(true); }