public static void DeleteCurrentUserFromCache() { FileFolderHelper.CheckAndDeleteFile(FileFolderHelper.LastUserFilePath); FileFolderHelper.CheckAndDeleteFile(FileFolderHelper.StorageFilePath); Logger.Log($"\t{CurrentUser.ToString()} successfuly deleted from cach on this PC"); CurrentUser = null; }
internal static TObject Deserialize <TObject>(string filePath) where TObject : class { try { if (!FileFolderHelper.CreateFolderAndCheckFileExistance(filePath)) { throw new FileNotFoundException("File doesn't exist."); } var formatter = new BinaryFormatter(); using (var stream = new FileStream(filePath, FileMode.Open)) { return((TObject)formatter.Deserialize(stream)); } } catch (FileNotFoundException ex) { Console.WriteLine(ex.Message); throw new FileNotFoundException($"Failed to Deserialize Data From File {filePath}", ex); } catch (Exception ex) { Console.WriteLine(ex.Message); throw new Exception($"Failed to Deserialize Data From File {filePath}", ex); } }
private void ChooseIndexingDir(String path) { LoadStatus = new bool[4]; _indexesTimeSpent = new TimeSpan[4]; int id = StationManager.DataStorage.GetPathNum(path); _model = new IndexModel(path, FileFolderHelper.CreateOrPickIndexesFolder(id)); // creating a model to test C++ then ViewModelsSynchronizer._indexModel = _model; OnPropertyChanged("WholeDirSize"); }
// loading user from appdata folder // and deserialize it public static void LoadCurrentUserFromCache() { if (FileFolderHelper.FileExists(FileFolderHelper.LastUserFilePath)) { } CurrentUser = SerializationManager.Deserialize <User>(FileFolderHelper.LastUserFilePath); if (CurrentUser != null) { Logger.Log($"\t{CurrentUser.ToString()} succsesfuly auto sign in"); } }
// Clears serialized file private void DestroySerializedUser() { try { FileFolderHelper.ClearFile(FileFolderHelper.LastUserFilePath); } catch (Exception e) { MessageManager.Log("Failed to clear last user in the file", e); } }
internal static void Serialize <TObject>(TObject obj, string filePath) { try { FileFolderHelper.CheckAndCreateFile(filePath); var formatter = new BinaryFormatter(); using (var stream = new FileStream(filePath, FileMode.Create)) { formatter.Serialize(stream, obj); } } catch (Exception) { throw; } }
internal static void Serialize <T>(T obj, string filePath) { try { FileFolderHelper.CheckAndCreateFile(filePath); var formatter = new BinaryFormatter(); using (var stream = new FileStream(filePath, FileMode.Create)) { formatter.Serialize(stream, obj); } } catch (Exception ex) { Logger.Log($"Failed to serialize data to file {filePath}", ex); throw; } }
internal static TObject Deserialize <TObject>(string filePath) where TObject : class { try { FileFolderHelper.CheckAndCreateFile(filePath); var formatter = new BinaryFormatter(); using (var stream = new FileStream(filePath, FileMode.Open)) { return((TObject)formatter.Deserialize(stream)); } } catch (Exception ex) { Logger.Log($"Failed to Deserialize Data From File {filePath}", ex); return(null); } }
public static void LoadUsers() { if (FileFolderHelper.FileExists(FileFolderHelper.LastUserFilePath)) { CurrentUsers = SerializationManager.Deserialize <List <Person> >(FileFolderHelper.LastUserFilePath); } else { var random = new Random(); for (var i = 0; i < 50; ++i) { var name = Names[random.Next(Names.Length)]; var surname = Surnames[random.Next(Surnames.Length)]; CurrentUsers.Add(new Person(name, surname, $"{name}.{surname}@gmail.com", DateTime.Now.AddYears(-random.Next(10, 80)).AddDays(-random.Next(31)).AddMonths(-random.Next(12)))); } } }
public static void Serialize <TObject>(TObject obj, string filePath) { try { FileFolderHelper.CheckAndCreateFile(filePath); var formatter = new BinaryFormatter(); using (var stream = new FileStream(filePath, FileMode.Create)) { formatter.Serialize(stream, obj); } } catch (Exception ex) { MessageBox.Show("SerializationFail" + ex.ToString()); Logger.Log($"Failed to serialize data to file {filePath}", ex); throw; } }
/// <summary> /// Deserialize object from file and return it. If file is empty, return null. /// </summary> /// <typeparam name="TObject">type of object to deserialize</typeparam> /// <param name="filePath"></param> /// <returns>deserialized object</returns> internal static TObject Deserialize <TObject>(string filePath) where TObject : class { try { if (!FileFolderHelper.CreateFolderAndCheckFileExistance(filePath)) { throw new FileNotFoundException("File doesn't exist."); } var formatter = new BinaryFormatter(); using (var stream = new FileStream(filePath, FileMode.Open)) { // if file is empty, return null return(stream.Length == 0 ? null : (TObject)formatter.Deserialize(stream)); } } catch (FileNotFoundException ex) { throw new FileNotFoundException($"Failed to Deserialize Data From File {filePath}", ex); } catch (Exception ex) { throw new Exception($"Failed to Deserialize Data From File {filePath}", ex); } }
// delete serialized user from appdata folder // after SignOut public static void RemoveCurrentUserFromCache() { FileFolderHelper.CheckAndDeleteFile(FileFolderHelper.LastUserFilePath); Logger.Log($"\t{CurrentUser.ToString()} was removed from auto sign in"); CurrentUser = null; }
/// <summary> ///多文件上传,返回多文件 /// </summary> /// <param name="context"></param> /// <param name="subFolder">人口照片、poi等文件夹名称</param> /// <param name="resetName">是否只返回文件名称</param> /// <returns></returns> public List <string> SaveUploadFileList(HttpContext context, string subFolder, bool resetName = true) { string strFileFullPath = string.Empty;//文件完整路径 string strRootPath = ConfigurationManager.AppSettings["imgFolderPath"].ToString() + subFolder + "\\"; List <string> listImge = new List <string>(); try { //验证父级文件夹,如果不存在 则创建 if (!Directory.Exists(strRootPath)) { Directory.CreateDirectory(strRootPath); } ///遍历File表单元素 HttpFileCollection files = context.Request.Files; for (int iFile = 0; iFile < files.Count; iFile++) { strFileName = ""; suffix = ""; ///检查文件扩展名字 HttpPostedFile postedFile = files[iFile]; filePath = postedFile.FileName; float fileSize = (postedFile.ContentLength / 1024.0f) / 1024.0f; if (fileSize > fileMaxSize) { } else { fileName = System.IO.Path.GetFileName(postedFile.FileName); if ("" != fileName) { string fileNewName = ResetFileName(fileName); strFileFullPath = strRootPath + fileNewName; //判断目录中是否已经存在此文件 if (FileFolderHelper.IsFileExist(strFileFullPath)) { //暂不处理 } else { postedFile.SaveAs(strFileFullPath);//保存图片 if (resetName) { listImge.Add(fileNewName);//将新定义的图片名称返回 } else { listImge.Add(subFolder + "\\" + fileNewName);//将新定义的图片名称返回 } } } else { listImge.Add(""); } } } } catch (Exception ex) { Log.Error("文件上传出错,详情:" + ex.ToString()); } return(listImge); }
public async Task <IActionResult> ModifyFilenameAsync(string id) { string newFileName = ""; string newDirFullPath = ""; string dirFullpath = DirectoryHelper.GetCodeDirectoryPath(); string reqBody = ""; await System.Threading.Tasks.Task.FromResult(0); // try { //read request body using (var reader = new StreamReader(Request.Body)) { var body = reader.ReadToEnd(); reqBody = body.ToString(); } //get new filename if (!string.IsNullOrEmpty(reqBody)) { var content = JObject.Parse(reqBody); newFileName = (string)content["newName"]; newFileName = Regex.Replace(newFileName, "[\n\r\t]", string.Empty); newFileName = Regex.Replace(newFileName, @"\s", string.Empty); } //if same name exist - BadRequest foreach (var record in codeResponse) { if (record.Id.ToLower() == newFileName.ToLower()) { return(BadRequest(new { message = "File with same name already exists." })); } } if (!string.IsNullOrEmpty(newFileName)) { //rename the file and/or folder foreach (var record in codeResponse) { if (record.Id.ToString() == id) { if (record.Type == "JUPYTER_NOTEBOOK") { //check if folder path exists...if not then move folder newDirFullPath = $"{dirFullpath}{newFileName}"; if (!Directory.Exists(newDirFullPath)) { Directory.Move($"{dirFullpath}{id}", newDirFullPath); FileFolderHelper.RenameFile($"{newDirFullPath}/{id}.{record.Extension}", $"{newDirFullPath}/{newFileName}.{record.Extension}"); newDirFullPath = $"{newDirFullPath}/{newFileName}.{record.Extension}"; } else { return(BadRequest(new { message = "Folder with same name already exists. Please choose different file/folder name." })); } } else { newDirFullPath = record.FilePath.Replace($"{id}.{record.Extension}", $"{newFileName}.{record.Extension}"); FileFolderHelper.RenameFile(record.FilePath, newDirFullPath); } //update GlobalStorage dictionary CodeResponse newRecord = new CodeResponse() { Id = newFileName, Name = $"{newFileName}.{record.Extension}", User = "", Created_on = record.Created_on, Edited_on = record.Edited_on, Extension = record.Extension, MimeType = record.MimeType, Size = record.Size, Type = record.Type, Url = record.Url.Replace(id, newFileName), FilePath = newDirFullPath, DateCreated = record.DateCreated }; CodePayload.Create(newRecord); CodePayload.RemoveOnlyFromCodePayload(id); return(Json(newRecord)); } } } } catch (Exception ex) { return(BadRequest(new { message = "Renaming file failed.", exception = ex.StackTrace })); } return(BadRequest(new { message = "Renaming file failed." })); }
public async Task <IActionResult> ModifyFilenameAsync(string id) { string newFileName = ""; string reqBody = ""; await System.Threading.Tasks.Task.FromResult(0); try { //read request body using (var reader = new StreamReader(Request.Body)) { var body = reader.ReadToEnd(); reqBody = body.ToString(); } //get new filename if (!string.IsNullOrEmpty(reqBody)) { var content = JObject.Parse(reqBody); newFileName = (string)content["newName"]; newFileName = Regex.Replace(newFileName, "[\n\r\t]", string.Empty); newFileName = Regex.Replace(newFileName, @"\s", string.Empty); } if (!string.IsNullOrEmpty(newFileName)) { //if same name exist - BadRequest foreach (var record in responseData) { if (record.Id.ToLower() == newFileName.ToLower()) { return(BadRequest(new { message = "File with same name already exists." })); } } //rename the file and/or folder foreach (var record in responseData) { if (record.Id.ToString() == id) { var newfilePath = record.FilePath.Replace($"{id}.{record.Extension}", $"{newFileName}.{record.Extension}"); FileFolderHelper.RenameFile(record.FilePath, newfilePath); var newRecord = new ModelResponse() { Created_on = record.Created_on, Edited_on = record.Edited_on, Extension = record.Extension, FilePath = newfilePath, Id = newFileName, MimeType = record.MimeType, Name = $"{newFileName}.{record.Extension}", Properties = record.Properties, Size = record.Size, Type = record.Type, Url = record.Url.Replace(id, newFileName), User = record.User }; ModelPayload.Create(newRecord); ModelPayload.RemoveOnlyFromModelPayload(id); return(Json(newRecord)); } } } } catch (Exception ex) { return(BadRequest(new { message = "Renaming file failed.", exception = ex.StackTrace })); } return(BadRequest(new { message = "Renaming file failed." })); }