private void FileZip_Click(object sender, RoutedEventArgs e) { if (string.IsNullOrEmpty(SavePath.Text)) { WinForms.MessageBox.Show("Please select your file.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information); SavePath.Focus(); return; } string filename = SavePath.Text; Thread thread = new Thread(t => { using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile()) { FileInfo fi = new FileInfo(filename); zip.AddFile(filename); System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(filename); zip.SaveProgress += Zip_SaveFileProgress; zip.Save(string.Format($"{di.Parent.FullName}/{di.Name}.zip")); } }) { IsBackground = true }; thread.Start(); }
public void ArchiveRecords(int matchNum) { string subPath = SavePath + (SavePath.EndsWith("\\") ? "" : "\\") + matchNum.ToString() + "\\"; Directory.CreateDirectory(subPath); List <string> files = Directory.EnumerateFiles(SavePath, "*" + ScoutingJson.MatchRecordExtension, SearchOption.TopDirectoryOnly).ToList(); foreach (string file in files) { try { File.Move(file, subPath + Util.GetFileName(file, true)); } catch (Exception e) { string msg = "Could not move file " + Util.GetFileName(file, true); Util.DebugLog(LogLevel.Error, msg); MessageBox.Show(msg + "\n\n" + e.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error); ProcessAllNewFolders = false; return; } } }
/// <summary> /// Try load data by file name and type. /// </summary> /// <param name="_name"> File name. </param> /// <param name="_data"> Save data. </param> /// <typeparam name="T"> Data type. </typeparam> private static bool TryLoadData <T>(string _name, out T _data) where T : SaveData { try { string _path = SavePath.GetName() + _name; _data = default; if (File.Exists(_path) == false) { return(false); } FileStream _stream = new FileStream(_path, FileMode.Open, FileAccess.Read, FileShare.None); _data = (T)binaryFormatter.Value.Deserialize(_stream); _stream.Close(); } catch (Exception _exception) { Debugger.Log($"Loading data failed: {_exception.Message}"); _data = null; return(false); } return(true); }
public void SaveProgramPath(List <string> path) { string pathText = List2String(path); SaveProgramPath(pathText); SavePath.Raise(this, null); }
private void OpenToolStripMenuItem_Click(object sender, EventArgs e) { try { if (MainPanel.PalSource != null) { switch (MyMessageBox.Show(Language.DICT["MainTitle"], Language.DICT["MsgInfoHintForSave"], MyMessageBoxButtons.YesNoCancel)) { case DialogResult.Yes: SaveToolStripMenuItem_Click(null, new EventArgs()); break; case DialogResult.No: break; default: return; } } OpenFileDialog openFileDialog = new OpenFileDialog { Filter = "Palette File|*.pal|All Files|*.*", InitialDirectory = Application.StartupPath, Title = Language.DICT["MainTitle"], DefaultExt = "pal", CheckPathExists = true }; if (openFileDialog.ShowDialog() == DialogResult.OK) { if (SavePath.EndsWith(".ini")) { //TODO } else { SavePath = openFileDialog.FileName; IsSaved = true; Undos.Clear(); Redos.Clear(); MainPanel.Selections.Clear(); MainPanel.PalSource = new PalFile(SavePath); MainPanel.Refresh(); MainPanel_SelectedIndexChanged(null, new EventArgs()); MainPanel_BackColorChanged(null, new EventArgs()); UpdateTitle(Language.DICT["MainTitleEmptyName"]); CurrentStatusLabel.Text = Language.DICT["StslblOpenSucceed"]; } } } catch (Exception ex) { SavePath = ""; IsSaved = false; MainPanel.Close(); CurrentStatusLabel.Text = Language.DICT["StslblOpenFailed"]; UpdateTitle(Language.DICT["MainTitleEmptyName"]); MyMessageBox.Show(Language.DICT["MainTitle"], Language.DICT["MsgFatalOpen"] + ex.Message); } }
/// <summary> /// Write data in file. /// </summary> private static void WriteInFile <T>(T _data) where T : SaveData { string _filePath = SavePath.GetName() + _data.Name; FileStream _stream = new FileStream(_filePath, FileMode.Create, FileAccess.Write, FileShare.None); binaryFormatter.Value.Serialize(_stream, _data); _stream.Close(); }
private void Selectpath_Click(object sender, EventArgs e) { DialogResult result = SavePath.ShowDialog(); if (result == DialogResult.OK || result == DialogResult.Yes) { PathText.Text = SavePath.SelectedPath; SetupTitle.Text = "设置"; } }
/// <summary> /// HttpPostedFile /// </summary> public void AliyunUploadFile() { //文件后缀 string Ext = GetExt(_FormFile.FileName); //获得文件大小,以字节为单位 long FileLength = _FormFile.ContentLength; if (_FormFile == null || _FormFile.FileName.Trim() == "") { Message = "请选择要上传文件!"; return; } if (!IsUpload(Ext)) { Message = "不允许上传" + Ext + "类型的文件!"; return; } if (FileLength > _MaxSize) { Message = "文件超过限制的大小!"; return; } try { //文件名 string FileName = _FormFile.FileName; if (IsChangeFileName) { FileName = GetFileName(Ext); } var fileStream = _FormFile.InputStream; var savedImagePath = imageStorage.Save("", SavePath.ToLower() + "/" + FileName, fileStream); //返回 OutFileName = GetFileName(_FormFile.FileName, Ext); OutFileExt = Ext; ToSavePath = savedImagePath.ToString(); FileSize = FileLength; ToFileSize = GetToFileSize(FileSize); Success = true; Message = "上传成功"; return; } catch (Exception ex) { Message = "上传失败!"; return; } }
public void Save() { if (SavePath.Trim().Length == 0) { SelectSavePath(); } if (SavePath.Trim().Length == 0) { return; } Save(SavePath); }
private bool LoadOld() { var updateSource = SavePath.Replace(".tmp", ""); if (!File.Exists(updateSource)) { Log.ErrorFormat("There is no gem file that can be updated (path: {0})", updateSource); return(false); } ItemDB.LoadFromCompletePath(updateSource); return(true); }
static void Writelittlesheep() { LoadCurSelection(); foreach (GameObject obj in curSelections) { if (obj.GetComponent <SavePath>() == null) { obj.AddComponent <SavePath>(); } SavePath path = obj.GetComponent <SavePath>(); path.PaintPath(); path.ClearOtherSavePath(); path.enabled = true; } }
/// <summary> /// Remove all data files. /// </summary> public static void RemoveAll() { try { string[] _names = Directory.GetFiles(SavePath.GetName()); for (int i = 0; i < _names.Length; i++) { File.Delete(_names[i]); } } catch (Exception _exception) { Debugger.Log($"Deleting all files failed: {_exception.Message}"); } }
/// <summary> /// Check if data file was created in default directory. /// </summary> /// <param name="_name"> File name. </param> /// <typeparam name="T"> Data type. </typeparam> /// <returns></returns> private static bool CheckIsCreated <T>(string _name) { string _path = SavePath.GetName() + _name; if (File.Exists(_path) == false) { return(false); } if (IsPathValid <T>(_name) == false) { return(false); } return(true); }
public void LoadFromFile(string _fileName, SavePath _savePath, SaveFormat _format) { var _path = ""; DataFormat _f = DataFormat.JSON; byte[] bytes = null; switch (_format) { case SaveFormat.json: _f = DataFormat.JSON; break; case SaveFormat.binary: _f = DataFormat.Binary; break; } switch (_savePath) { case SavePath.PlayerPrefs: string _loadString = PlayerPrefs.GetString(_fileName); bytes = System.Convert.FromBase64String(_loadString); variables = SerializationUtility.DeserializeValue <OrderedDictionary <Guid, FRVariable> >(bytes, _f); break; case SavePath.PersistentPath: _path = System.IO.Path.Combine(Application.persistentDataPath, _fileName); bytes = File.ReadAllBytes(_path); variables = SerializationUtility.DeserializeValue <OrderedDictionary <Guid, FRVariable> >(bytes, _f); break; case SavePath.StreamingAssets: _path = System.IO.Path.Combine(Application.streamingAssetsPath, _fileName); bytes = File.ReadAllBytes(_path); variables = SerializationUtility.DeserializeValue <OrderedDictionary <Guid, FRVariable> >(bytes, _f); break; } }
/// <summary> /// Returns the path towards the save location selected in the settings. /// If for some reason it can't do so, it will return the Application.persistentDataPath instead. /// </summary> private static string GetPathToSaveLocation(SavePath location) { switch (location) { case SavePath.PersistentPath: return(Path.Combine(Application.persistentDataPath, settings.directoryName)); case SavePath.ApplicationPath: return(Path.Combine(Application.dataPath, settings.directoryName)); case SavePath.Documents: return(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), settings.directoryName)); default: Debug.LogWarning("Couldn't get the desired path to save location, using Application.persistentDataPath instead."); return(Path.Combine(Application.persistentDataPath, directory.Name)); } }
/// <summary> /// Checks if a save file exists in the specified path, /// sing the save files directory in the search. /// </summary> /// <param name="path"> What path to search for the file? </param> /// <param name="name"> What is the name of the file to check for? </param> /// <returns></returns> public static bool CheckForSaveFile(SavePath path, string name) { switch (path) { case SavePath.PersistentPath: return(CheckForSaveFile(Path.Combine(Application.persistentDataPath, settings.directoryName, name))); case SavePath.ApplicationPath: return(CheckForSaveFile(Path.Combine(Application.dataPath, settings.directoryName, name))); case SavePath.Documents: return(CheckForSaveFile(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), Application.companyName, Application.productName, settings.directoryName, name))); default: Debug.LogWarning("Couldn't find the specified file."); return(false); } }
public Project() { IsValid = AssemblyPath.CombineLatest(ProjectTypeName, (x, y) => { if (x == null || !File.Exists(GetProjectsContentPath(x))) { return(false); } else { return(GetProjectType(GetAssembly()) != null); } }).CombineLatest(SavePath.Select(x => x != null), (x, y) => x && y) .ToReactiveProperty(); Dependencies = dependencies_.ToReadOnlyReactiveCollection(); Factory = new PropertyFactory(); }
/// <summary> /// 表格文字识别 /// </summary> /// <param name="path"></param> /// <param name="img"></param> /// <returns></returns> public static string FormOcrRequest(string downloadDir, Image img) { string url = "https://openapi.youdao.com/ocr_table"; string base64 = WebExt.ImageToBase64(img); string salt = DateTime.Now.Millisecond.ToString(); string curTime = WebExt.GetTimeSpan(); string sign = ComputeHash(YoudaoKey.AppKey + Truncate(base64) + salt + curTime + YoudaoKey.AppSecret); string str = string.Format($"q={HttpUtility.UrlEncode(base64)}" + $"&type=1&appKey={YoudaoKey.AppKey}" + $"&salt={salt}&sign={sign}&docType=excel&signType=v3&curtime={curTime}"); string result = WebExt.Request(url, null, str); // 解析json数据 JavaScriptSerializer js = new JavaScriptSerializer(); string json_result = GetDictResult(result); JsonForm list = js.Deserialize <JsonForm>(json_result); if (list.tables.Count == 0) { throw new Exception("识别失败!"); } // 将接收到的base64数据写入到xlsx文件 if (downloadDir == null) { return(string.Format("识别成功。\r\n返回的Base64编码:\r\n{0}", string.Join("", list.tables.ToArray()))); } string downloadPath = new SavePath().FormPath + DateTime.Now.ToString("yyyy-MM-dd_HH_mm_ss") + ".xlsx"; if (!Directory.Exists(Path.GetDirectoryName(downloadPath))) { Directory.CreateDirectory(Path.GetDirectoryName(downloadPath)); } using (FileStream fs = new FileStream(downloadPath, FileMode.Create)) { foreach (var cont in list.tables) { byte[] contents = Convert.FromBase64String(cont); fs.Write(contents, 0, contents.Length); } } return(string.Format("识别成功,已下载到当前程序目录。\r\n返回的Base64编码:\r\n{0}", string.Join("", list.tables.ToArray()))); }
public void SaveToFile(string _fileName, SavePath _savePath, SaveFormat _format) { var _path = ""; DataFormat _f = DataFormat.JSON; byte[] bytes = null; switch (_format) { case SaveFormat.json: _f = DataFormat.JSON; break; case SaveFormat.binary: _f = DataFormat.Binary; break; } switch (_savePath) { case SavePath.PlayerPrefs: bytes = SerializationUtility.SerializeValue(variables, _f); string _saveString = System.Convert.ToBase64String(bytes); PlayerPrefs.SetString(_fileName, _saveString); break; case SavePath.PersistentPath: _path = System.IO.Path.Combine(Application.persistentDataPath, _fileName); bytes = SerializationUtility.SerializeValue(variables, _f); File.WriteAllBytes(_path, bytes); break; case SavePath.StreamingAssets: _path = System.IO.Path.Combine(Application.streamingAssetsPath, _fileName); bytes = SerializationUtility.SerializeValue(variables, _f); File.WriteAllBytes(_path, bytes); break; } }
public void SelectSavePath() { var dir = SavePath; var path = SavePath.GetSuffix(); if (path != string.Empty) { dir = dir.Replace(path, ""); } var dialog = new SaveFileDialog(); dialog.InitialDirectory = dir; dialog.FileName = path; dialog.Filter = "NPK|*.npk"; if (dialog.ShowDialog() == DialogResult.OK) { SavePath = dialog.FileName; OnSaveChanged(); } }
} // Extension of the Original Image. #endregion /// <summary> /// Extract the Sub Sprites of a Sprite Sheet using the Metadata generated by using the Unity Sprite Editor. /// </summary> public void ExtractSprites() { // Get The meta Data of the Sub Sprite Artwork. _subSprites = AssetDatabase.LoadAllAssetRepresentationsAtPath(SpriteSheetPath); for (int i = 0; i < _subSprites.Length; i++) { _subTexture = ((Sprite)_subSprites[i]).texture; _subTextureRect = ((Sprite)_subSprites[i]).textureRect; _extractedTexture = _subTexture.CropTexture2D((int)_subTextureRect.x, (int)_subTextureRect.y, (int)_subTextureRect.width, (int)_subTextureRect.height); data = _extractedTexture.EncodeToPNG(); File.WriteAllBytes(SavePath.Combine("/", ((Sprite)_subSprites[i]).name, ".png"), data); } AssetDatabase.Refresh(); }
private void button4_Click(object sender, EventArgs e) { string SavePath; if (this.PicturePath != null) { SavePath = System.IO.Path.GetDirectoryName(this.PicturePath) + "\\" + System.IO.Path.GetFileNameWithoutExtension(this.PicturePath); } else { SavePath = System.Reflection.Assembly.GetExecutingAssembly().CodeBase; SavePath = System.IO.Path.GetDirectoryName(SavePath); SavePath = SavePath.Replace("file:\\", ""); } this.pictureBox19.Image.Save(SavePath + "_letter1.png", System.Drawing.Imaging.ImageFormat.Png); this.pictureBox17.Image.Save(SavePath + "_letter2.png", System.Drawing.Imaging.ImageFormat.Png); this.pictureBox18.Image.Save(SavePath + "_letter3.png", System.Drawing.Imaging.ImageFormat.Png); this.pictureBox16.Image.Save(SavePath + "_letter4.png", System.Drawing.Imaging.ImageFormat.Png); }
private void button3_Click(object sender, EventArgs e) { string SavePath; if (this.PicturePath != null) { SavePath = System.IO.Path.GetDirectoryName(this.PicturePath) + "\\" + System.IO.Path.GetFileNameWithoutExtension(this.PicturePath); } else { SavePath = System.Reflection.Assembly.GetExecutingAssembly().CodeBase; SavePath = System.IO.Path.GetDirectoryName(SavePath); SavePath = SavePath.Replace("file:\\", ""); } this.pictureBox3.Image.Save(SavePath + "_nobg.png", System.Drawing.Imaging.ImageFormat.Png); this.pictureBox5.Image.Save(SavePath + "_arcinletter.png", System.Drawing.Imaging.ImageFormat.Png); this.pictureBox2.Image.Save(SavePath + "_noartifacts.png", System.Drawing.Imaging.ImageFormat.Png); this.pictureBox4.Image.Save(SavePath + "_binarised.png", System.Drawing.Imaging.ImageFormat.Png); this.pictureBox7.Image.Save(SavePath + "_segmented.png", System.Drawing.Imaging.ImageFormat.Png); }
/// <summary> /// Check if file corresponds the requested type. /// </summary> /// <param name="_name"> File name. </param> /// <typeparam name="T"> Data type. </typeparam> private static bool IsPathValid <T>(string _name) { string _path = SavePath.GetName() + _name; if (File.Exists(_path) == false) { return(true); } FileStream _stream = new FileStream(_path, FileMode.Open); object _data = binaryFormatter.Value.Deserialize(_stream); _stream.Close(); if (_data is T) { return(true); } return(false); }
private static void InitSavePath() { if (App.Steam) { // Save to Steam user folder string savePath; CheckSteamworksResult("SteamUser.GetUserDataFolder", SteamUser.GetUserDataFolder(out savePath, 4096)); SavePath = savePath; } else if (App.Debug) { // Save to Debug directory SavePath = "../Saves".Replace('/', Path.DirectorySeparatorChar); } else { // Save to SDL2 directory SavePath = SDL.SDL_GetPrefPath(App.Info.DeveloperName, App.Info.Title); App.CheckSDLResult("SDL_GetPrefPath", SavePath); SavePath = SavePath.Replace(App.Info.DeveloperName + Path.DirectorySeparatorChar, ""); Directory.CreateDirectory(SavePath); } }
private void BeginCreateCb(IAsyncResult result) { logger.Debug("Torrent creation finished"); progressDialog.Destroy(); try{ BEncodedDictionary dict = creator.EndCreate(result); string p = savePathChooser.Filename; if (!p.EndsWith(".torrent", StringComparison.OrdinalIgnoreCase)) { p = p + ".torrent"; } System.IO.File.WriteAllBytes(p, dict.Encode()); if (startSeedingCheckBox.Active) { Torrent t = Torrent.Load(p); BitField bf = new BitField(t.Pieces.Count); bf.Not(); MonoTorrent.Client.FastResume fresume = new MonoTorrent.Client.FastResume(t.InfoHash, bf); torrentController.FastResume.Add(fresume); string savePath; if (newTorrentLocationButton.Action == FileChooserAction.SelectFolder) { savePath = SavePath.Substring(0, SavePath.LastIndexOf('/')); } else { savePath = System.IO.Path.GetDirectoryName(SavePath); } torrentController.addTorrent(t, savePath, startSeedingCheckBox.Active); } logger.Debug("Torrent file created"); }catch (Exception e) { logger.Error("Failed to create torrent - " + e.ToString()); } }
public static bool ConvertFileNameAt(int index) { string newFileName = string.Empty; FileMusic muFile = (FileMusic)FileLists.ElementAt(index); if (string.IsNullOrEmpty(muFile.Artist) && string.IsNullOrEmpty(muFile.Title)) { newFileName = muFile.FileName; } else { newFileName = string.Concat("[", muFile.Artist, "]", muFile.Title, ".mp3"); } if (SavePath.Equals(string.Empty)) { return(false); } if (!Directory.Exists(@SavePath)) { Directory.CreateDirectory(@SavePath); } try { var sourceFile = string.Concat(FileLists.ElementAt(index).FilePath, "\\", FileLists.ElementAt(index).FileName); File.Copy(sourceFile, string.Concat(@SavePath, "//", newFileName), true); File.Delete(sourceFile); } catch (Exception ex) { } return(true); }
private void SavePreview() { Debug.Log("Saving preview for the GIF"); RenderTexture oldRT = RenderTexture.active; RenderTexture[] frames = m_Frames.ToArray(); RenderTexture.active = frames[(int)frames.Length / 2]; Texture2D target = new Texture2D(m_Width, m_Height, TextureFormat.ARGB32, false); target.hideFlags = HideFlags.HideAndDontSave; target.wrapMode = TextureWrapMode.Clamp; target.filterMode = FilterMode.Bilinear; target.anisoLevel = 0; target.ReadPixels(new Rect(0, 0, m_Width, m_Height), 0, 0); target.Apply(); RenderTexture.active = oldRT; byte[] bytes = target.EncodeToPNG(); System.IO.File.WriteAllBytes(SavePath.Replace(".gif", ".png"), bytes); Flush(target); }
/// <summary> /// 储存文件并返回结果 /// </summary> /// <returns>Bool</returns> public bool Save() { if (!Directory.Exists(sv.MapPath(SavePath))) { Directory.CreateDirectory(sv.MapPath(SavePath)); } if (ReqFile == null) { Err = 4; return(false); } if (ReqFile.ContentLength > MaxSize) { Err = 1; return(false); } var fil = Filter.Where(m => m == Path.GetExtension(ReqFile.FileName.ToLower())); string TempFilePath = TempFolder.EndsWith("/") ? TempFolder + NewFileName : TempFolder + "/" + NewFileName; string NewFilepath = SavePath.EndsWith("/") ? SavePath + NewFileName : SavePath + "/" + NewFileName; if (fil.Count() != 1) { Err = 2; return(false); } if (SafePicture) { try { var rawimg = Image.FromStream(ReqFile.InputStream); rawimg.Dispose(); } catch (Exception) { Err = 2; return(false); } } try { ReqFile.SaveAs(sv.MapPath(TempFilePath)); } catch (Exception) { Err = 3; return(false); } if (Resize) { IASPJpeg j = new ASPJpeg(); j.Open(sv.MapPath(TempFilePath)); j.Quality = 80; int ow = j.OriginalWidth; int oh = j.OriginalHeight; if (ow > MaxWidth) { j.Width = MaxWidth; if (Constrain) { j.Height = (int)((MaxWidth.CDbl() / ow.CDbl()) * oh.CDbl()); if (Crop && j.Height > MaxHeight) { j.Crop(0, (j.Height - MaxHeight) / 2, j.Width, MaxHeight + (j.Height - MaxHeight) / 2); } } else { j.Height = MaxHeight; } } j.Save(sv.MapPath(NewFilepath)); StoredPath = NewFilepath; File.Delete(sv.MapPath(TempFilePath)); return(true); } else { File.Move(sv.MapPath(TempFilePath), sv.MapPath(NewFilepath)); StoredPath = NewFilepath; return(true); } }
/// <summary> /// Delete file from default directory. /// </summary> /// <param name="_name"> File name. </param> private static void DeleteFile(string _name) { string _path = SavePath.GetName() + _name; File.Delete(_path); }