public void ExportToExcel() { var dialog = new CommonSaveFileDialog(); dialog.Filters.Add(new CommonFileDialogFilter("excel file", "*.xlsx")); dialog.DefaultExtension = "xlsx"; if (dialog.ShowDialog() != CommonFileDialogResult.Ok) { return; } try { var dataTable = this.tableViewModel.Source.ExportTable2(); var writer = new SpreadsheetWriter(dataTable.DataSet); writer.Write(dialog.FileName); } catch (Exception e) { AppMessageBox.ShowError(e); } }
public static async Task SaveAttachment(string url) { CommonSaveFileDialog dialog = new CommonSaveFileDialog(); dialog.Title = "Save image as..."; dialog.Filters.Add(new CommonFileDialogFilter("Original file extension", Path.GetExtension(url))); dialog.DefaultFileName = Path.GetFileName(url); if (dialog.ShowDialog() == CommonFileDialogResult.Ok) { App.DiscordWindow.StatusShowWarning($"Downloading {Path.GetFileName(dialog.FileName)}...", false, false); using (HttpClient client = new HttpClient()) { using (Stream str = await client.GetStreamAsync(url)) { using (FileStream file = File.OpenWrite(dialog.FileName)) { await str.CopyToAsync(file); } } } App.DiscordWindow.StatusShowSuccess($"Downloaded {Path.GetFileName(dialog.FileName)}!"); } }
private static string?GetSaveFileName(string defaultPath) { var dlg = new CommonSaveFileDialog { Title = @"另存为", AddToMostRecentlyUsedList = false, NavigateToShortcut = true, DefaultFileName = Path.GetFileName(defaultPath), DefaultExtension = Path.GetExtension(defaultPath), DefaultDirectory = Path.GetDirectoryName(defaultPath), Filters = { Constants.VideoFilter, Constants.AllFilter } }; if (dlg.ShowDialog() == CommonFileDialogResult.Ok) { return(dlg.FileName); } return(null); }
private void OnRequestSaveOtherFormatMessageData() { var sfd = new CommonSaveFileDialog() { Title = "Export Script Archive", DefaultExtension = "txt", AlwaysAppendDefaultExtension = true, }; sfd.Filters.Add(new CommonFileDialogFilter("Archives", "txt")); if (WSettingsManager.GetSettings().LastScriptArchivePath.FilePath != "") { sfd.InitialDirectory = WSettingsManager.GetSettings().LastScriptArchivePath.FilePath; } if (sfd.ShowDialog() == CommonFileDialogResult.Ok) { SaveMessageOther(sfd.FileName); WSettingsManager.GetSettings().LastScriptArchivePath.FilePath = Path.GetDirectoryName(sfd.FileName); WSettingsManager.SaveSettings(); } }
private void ExportTagsButton_Click(object sender, System.EventArgs e) { var dialog = new CommonSaveFileDialog(); dialog.DefaultFileName = "tags"; dialog.Filters.Add(new CommonFileDialogFilter("Tags file", TAGS_FILE_EXTENSION)); if (dialog.ShowDialog() == CommonFileDialogResult.Ok && !string.IsNullOrWhiteSpace(dialog.FileName)) { string json = null; if (getTagsFunc == null) { json = JsonConvert.SerializeObject(Settings.Default.Tags.Cast <string>()); } else { json = JsonConvert.SerializeObject(getTagsFunc.Invoke()); } File.WriteAllText(dialog.FileName + TAGS_FILE_EXTENSION, json); } }
private void saveAs(object sender, RoutedEventArgs e) { var vm = DataContext as MainVM; using (var dialog = new CommonSaveFileDialog()) { try { dialog.InitialDirectory = System.IO.Path.GetDirectoryName(vm.project.path); dialog.DefaultFileName = System.IO.Path.GetFileName(vm.project.path); } catch { } if (dialog.ShowDialog() == CommonFileDialogResult.Ok) { Directory.CreateDirectory(dialog.FileName); vm.project.path = dialog.FileName; // vm.project.generateFiles(); var dlg = new SaveProjectWin(new SaveWinVM(vm.project, vm.libManager, vm.setup)); dlg.ShowDialog(); } } }
public void SaveScreenshotToDisk() { if (SelectedDeck == null || DeckScreenshot == null) { return; } var invalid = new string(Path.GetInvalidFileNameChars()); var defaultFilename = invalid.Aggregate(this.DeckName, (current, c) => current.Replace(c.ToString(CultureInfo.InvariantCulture), "_")); defaultFilename += ".png"; var dialog = new CommonSaveFileDialog { OverwritePrompt = true, DefaultExtension = ".png", DefaultFileName = defaultFilename, EnsureValidNames = true, Title = "Save deck screenshot", AllowPropertyEditing = false, RestoreDirectory = true, Filters = { new CommonFileDialogFilter("PNG", ".png") } }; if (dialog.ShowDialog() == CommonFileDialogResult.Ok) { var filename = dialog.FileName; using (var fs = File.Create(filename)) { BitmapEncoder enc = new PngBitmapEncoder(); enc.Frames.Add(BitmapFrame.Create(DeckScreenshot)); enc.Save(fs); } } }
private void saveTxt() { StreamWriter file; CommonSaveFileDialog saveDialog; try { saveDialog = new CommonSaveFileDialog(); saveDialog.Title = "Save resume"; saveDialog.Filters.Add(new CommonFileDialogFilter("Text file", "txt")); saveDialog.DefaultExtension = "txt"; saveDialog.DefaultFileName = lblFilter.Content.ToString().Trim() + "_" + DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss") + ".txt"; if (saveDialog.ShowDialog() == CommonFileDialogResult.Ok) { file = new StreamWriter(saveDialog.FileName, false, System.Text.Encoding.UTF8); file.Write(getResumetext()); file.Close(); file.Dispose(); file = null; BMessage.Instance.fnMessage("Saved", "Bucket Report", MessageBoxButton.OK); } Topmost = true; Thread.Sleep(10); Topmost = false; } catch (Exception ex) { throw new Exception("Error saving report.", ex); } finally { Topmost = true; Thread.Sleep(10); Topmost = false; } }
private void btn_print_track_Click(object sender, RoutedEventArgs e) { if (IsLoaded) { btn_print_track.IsEnabled = false; string selectedId = labelToneId.Text; labelToneId.Text = num_meta_id.Value.ToString(); var dialog = new CommonSaveFileDialog(); dialog.AddToMostRecentlyUsedList = false; dialog.Title = "Where do you want to save the .pdf file?"; dialog.DefaultFileName = "Disk_" + num_meta_id.Value.ToString() + ".pdf"; dialog.DefaultExtension = "pdf"; dialog.Filters.Add(new CommonFileDialogFilter("PDF document", "pdf")); CommonFileDialogResult result = dialog.ShowDialog(); if (result == CommonFileDialogResult.Ok) { MemoryStream lMemoryStream = new MemoryStream(64 * 1024); Package package = Package.Open(lMemoryStream, FileMode.Create); XpsDocument doc = new XpsDocument(package); XpsDocumentWriter writer = XpsDocument.CreateXpsDocumentWriter(doc); writer.Write(ChartArea); doc.Close(); package.Close(); var pdfXpsDoc = PdfSharp.Xps.XpsModel.XpsDocument.Open(lMemoryStream); PdfSharp.Xps.XpsConverter.Convert(pdfXpsDoc, dialog.FileName, 0); labelToneId.Text = selectedId; } btn_print_track.IsEnabled = true; } }
private void buttonExport_Click(object sender, RoutedEventArgs e) { CommonSaveFileDialog dialogExportData = new CommonSaveFileDialog { Title = "Save exported data to...", DefaultFileName = "songdata.json", }; if (dialogExportData.ShowDialog() != CommonFileDialogResult.Ok) { return; // It's TIME to STOP! NO MORE! } List <DDRCardDrawDataSong> songs = new List <DDRCardDrawDataSong>(); foreach (Simfile file in simfiles) { songs.Add(DDRCardDrawData.simfileToCardDrawSong(file)); } string data = JsonConvert.SerializeObject(songs); File.WriteAllText(dialogExportData.FileName, data); }
private void SaveCSV() { StreamWriter file; CommonSaveFileDialog saveDialog; try { saveDialog = new CommonSaveFileDialog(); saveDialog.Title = "Save CSV file"; saveDialog.Filters.Add(new CommonFileDialogFilter("CSV file", "csv")); saveDialog.DefaultExtension = "csv"; saveDialog.DefaultFileName = lblFilter.Content.ToString().Trim() + "_" + DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss") + ".csv"; if (saveDialog.ShowDialog() == CommonFileDialogResult.Ok) { file = new StreamWriter(saveDialog.FileName, false, System.Text.Encoding.UTF8); file.WriteLine("number;title;kind;assignee;type;priority;state;component;milestone;version;reporter;created_on;updated_on"); issues.ForEach(issue => file.WriteLine(issue.ToString())); file.Close(); file.Dispose(); file = null; BMessage.Instance.fnMessage("Saved", "Bucket Report", MessageBoxButton.OK); } } catch (Exception ex) { throw new Exception("Error saving report.", ex); } finally { Topmost = true; Thread.Sleep(10); Topmost = false; } }
private void OnSaveFileDialogMessage(SaveFileDialogMessage message) { CommonSaveFileDialog csfd = new CommonSaveFileDialog { Title = message.Title, EnsurePathExists = true, DefaultFileName = message.DefaultFileName, DefaultExtension = message.DefaultFileExtension, EnsureValidNames = true }; CommonFileDialogResult sResult = csfd.ShowDialog(); csfd.Dispose(); if (sResult == CommonFileDialogResult.Ok) { message.Callback?.Invoke(true, csfd.FileName); } else { message.Callback?.Invoke(false, null); } }
private void ExportSF2(object sender, EventArgs e) { var d = new CommonSaveFileDialog { DefaultFileName = Engine.Instance.Config.GetGameName(), DefaultExtension = ".sf2", EnsureValidNames = true, Title = Strings.MenuSaveSF2, Filters = { new CommonFileDialogFilter(Strings.FilterSaveSF2, ".sf2") } }; if (d.ShowDialog() == CommonFileDialogResult.Ok) { try { Core.GBA.AlphaDream.SoundFontSaver_SF2.Save((Core.GBA.AlphaDream.Config)Engine.Instance.Config, d.FileName); FlexibleMessageBox.Show(string.Format(Strings.SuccessSaveSF2, d.FileName), Text); } catch (Exception ex) { FlexibleMessageBox.Show(ex, Strings.ErrorSaveSF2); } } }
private void SaveFileDialogCustomizationXamlClicked(object sender, RoutedEventArgs e) { CommonSaveFileDialog saveFileDialog = FindSaveFileDialog("CustomSaveFileDialog"); saveFileDialog.CookieIdentifier = saveDialogGuid; saveFileDialog.Filters.Add(new CommonFileDialogFilter("My App Type", "*.xyz")); saveFileDialog.DefaultExtension = "xyz"; saveFileDialog.AlwaysAppendDefaultExtension = true; saveFileDialog.Controls["textName"].Text = Environment.UserName; currentFileDialog = saveFileDialog; CommonFileDialogResult result = saveFileDialog.ShowDialog(); if (result == CommonFileDialogResult.Ok) { string output = "File Selected: " + saveFileDialog.FileName + Environment.NewLine; output += Environment.NewLine + GetCustomControlValues(); MessageBox.Show(output, "Save File Dialog Result", MessageBoxButton.OK, MessageBoxImage.Information); } }
public async Task <string> SavePlaylistDataAsync() { var fileDialog = new CommonSaveFileDialog { Title = "Save Playlist...", DefaultExtension = "m3u", AlwaysAppendDefaultExtension = true }; fileDialog.Filters.Add(new CommonFileDialogFilter("M3U Playlist Files", "*.m3u")); if (fileDialog.ShowDialog() != CommonFileDialogResult.Ok) { await Task.Delay(1); return(LoadedPlaylistFile); } ViewModelStatus = "Loading Playlist..."; var buffer = new StringBuilder(); var selectedFile = new FileInfo(fileDialog.FileName); foreach (var track in TrackList) { var filePath = Path.GetRelativePath(selectedFile.DirectoryName, track.ResolvedPath); buffer.AppendLine(filePath); } await PlaylistFileProcessor.SavePlaylistDataAsync(selectedFile.FullName, buffer.ToString()); ViewModelStatus = await Task.Run(() => GetPlaylistSummary()); return(selectedFile.FullName); }
private void NewTemplateButton_Click(object sender, RoutedEventArgs e) { using (var dlg = new CommonSaveFileDialog()) { dlg.Title = "Create new template file"; dlg.InitialDirectory = (string)TemplatesDirSelection.SelectedItem; dlg.AddToMostRecentlyUsedList = false; dlg.DefaultDirectory = TemplateFactory.GetInstance().TemplatesDirectory; dlg.EnsurePathExists = true; dlg.EnsureReadOnly = false; dlg.EnsureValidNames = true; dlg.ShowPlacesList = true; dlg.DefaultExtension = ".json"; dlg.Filters.Add(new CommonFileDialogFilter("json", ".json")); if (dlg.ShowDialog() == CommonFileDialogResult.Ok) { string path = dlg.FileName; TemplateFactory.GetInstance().CreateNewTemplate(path); SelectedTemplate = path; FilesList.Focus(); } } }
public void ExportCurvesToXLS() { var workbook = new XLWorkbook(); var worksheet = workbook.Worksheets.Add("Curve"); var trackKeys = new SortedDictionary <float, List <float> >(); // time is key, then all the floats at that time var curveList = new List <string>(); //List of column names //write data to list foreach (var track in InterpCurveTracks) { int n = 0; foreach (var curve in track.Curves) { n++; curveList.Add(curve.Name); foreach (var point in curve.CurvePoints) { float time = point.InVal; if (!trackKeys.ContainsKey(time)) { trackKeys.Add(time, new List <float>()); } else { while (trackKeys[time].Count < n - 1) //if previous curves didn't have this time add null [better way]? { trackKeys[time].Add((float)0.12345678); } } trackKeys[time].Add(point.OutVal); } } } //Write to XL int xlrow = 1; int xlcol = 1; worksheet.Cell(xlrow, xlcol).Value = "Time"; foreach (var cn in curveList) { xlcol++; worksheet.Cell(xlrow, xlcol).Value = cn; } foreach (var tk in trackKeys) { xlrow++; xlcol = 1; worksheet.Cell(xlrow, xlcol).Value = tk.Key.ToString(); foreach (var point in tk.Value) { xlcol++; if (point != (float)0.12345678) //skip null values { worksheet.Cell(xlrow, xlcol).Value = point.ToString(); } } } CommonSaveFileDialog m = new CommonSaveFileDialog { Title = "Select excel output", DefaultFileName = $"{CurrentLoadedExport.ObjectNameString}_{CurrentLoadedExport.UIndex}.xlsx", DefaultExtension = "xlsx", }; m.Filters.Add(new CommonFileDialogFilter("Excel Files", "*.xlsx")); var owner = Window.GetWindow(this); if (m.ShowDialog(owner) == CommonFileDialogResult.Ok) { owner.RestoreAndBringToFront(); try { workbook.SaveAs(m.FileName); MessageBox.Show($"Curves exported to {System.IO.Path.GetFileName(m.FileName)}."); } catch { MessageBox.Show($"Save to {System.IO.Path.GetFileName(m.FileName)} failed.\nCheck the excel file is not open."); } } }
public static string Save( [NotNull] string initialDirectory, [NotNull] string title, [NotNull] string filter, string defaultExt, bool overwritePrompt = true, [CanBeNull] string preselectFileName = null) { Retry: if (m_CommonFileDialogSupported) { using (var commonSaveFileDialog = new CommonSaveFileDialog(title)) { SetFilter(filter, commonSaveFileDialog.Filters); commonSaveFileDialog.InitialDirectory = initialDirectory.RemovePrefix(); commonSaveFileDialog.EnsurePathExists = true; commonSaveFileDialog.EnsureValidNames = true; commonSaveFileDialog.OverwritePrompt = overwritePrompt; commonSaveFileDialog.RestoreDirectory = true; if (!string.IsNullOrEmpty(preselectFileName)) { commonSaveFileDialog.DefaultFileName = preselectFileName; commonSaveFileDialog.DefaultExtension = defaultExt; } try { if (commonSaveFileDialog.ShowDialog() == CommonFileDialogResult.Ok && commonSaveFileDialog.FileAsShellObject.IsFileSystemObject) { // can not use commonSaveFileDialog.FileName the extension is wrong / first extension // of filter is added no matter what is entered in dialog return(((Microsoft.WindowsAPICodePack.Shell.ShellFile)commonSaveFileDialog.FileAsShellObject).Path.LongFileName()); } } catch (Exception exception) { Logger.Warning(exception, "Using CommonSaveFileDialog"); m_CommonFileDialogSupported = false; goto Retry; } } } else { using (var saveFileDialog = new SaveFileDialog()) { //saveFileDialog.DefaultExt = defaultExt; saveFileDialog.Filter = filter; saveFileDialog.OverwritePrompt = overwritePrompt; saveFileDialog.CheckFileExists = true; saveFileDialog.CheckPathExists = true; saveFileDialog.RestoreDirectory = true; saveFileDialog.Title = title; saveFileDialog.InitialDirectory = initialDirectory.RemovePrefix(); if (!string.IsNullOrEmpty(preselectFileName)) { saveFileDialog.FileName = preselectFileName; } if (saveFileDialog.ShowDialog() != DialogResult.OK) { return(saveFileDialog.FileName.LongFileName()); } } } return(null); }
public static void Main(string[] args) { ShowHideWindow.Show(false); CommonFileDialog dialog; var br = new BinaryReader(Console.OpenStandardInput()); var settings = FileBrowserSettings.Read(br); if (!settings.save) { dialog = new CommonOpenFileDialog(settings.title) { IsFolderPicker = settings.isFolderPicker, Multiselect = settings.multiSelect } } ; else { dialog = new CommonSaveFileDialog(settings.title) { AlwaysAppendDefaultExtension = true } }; using (dialog) { if (!string.IsNullOrEmpty(settings.title)) { dialog.Title = settings.title; } if (!string.IsNullOrEmpty(settings.defaultDirectory)) { dialog.InitialDirectory = settings.defaultDirectory; } if (!string.IsNullOrEmpty(settings.defaultFilename)) { dialog.DefaultFileName = settings.defaultFilename; } if (!string.IsNullOrEmpty(settings.defaultExtension)) { dialog.DefaultExtension = settings.defaultExtension; } try { if (!string.IsNullOrEmpty(settings.filters)) { foreach (var filter in settings.filters.Split(';')) { dialog.Filters.Add(new CommonFileDialogFilter(filter.Split('|')[0], filter.Split('|')[1])); } } } catch { Console.Error.WriteLine("Invalid filter list format"); } dialog.EnsureFileExists = true; dialog.EnsurePathExists = true; dialog.EnsureValidNames = true; switch (dialog.ShowDialog()) { case CommonFileDialogResult.Ok: if (dialog is CommonOpenFileDialog) { foreach (var file in (dialog as CommonOpenFileDialog).FileNames) { Console.WriteLine(file); } } else { Console.WriteLine(dialog.FileName); } break; } } } }
public virtual void EditorActionClick(EditorAction.ClickContext context) { switch (context.Action.Name) { case "Save": Save(null); break; case "Save As": { #if !PROJECT_DEPLOY var dialog = new CommonSaveFileDialog(); dialog.InitialDirectory = Path.GetDirectoryName(RealFileName); dialog.DefaultFileName = Path.GetFileName(RealFileName); dialog.Filters.Add(new CommonFileDialogFilter("All Files", ".*")); if (dialog.ShowDialog() != CommonFileDialogResult.Ok) { return; } var saveAsFileName = dialog.FileName; //if( File.Exists( saveAsFileName ) ) //{ // var text = string.Format( EditorLocalization.Translate( "General", "A file with the name \'{0}\' already exists. Overwrite?" ), saveAsFileName ); // if( EditorMessageBox.ShowQuestion( text, MessageBoxButtons.OKCancel ) != DialogResult.OK ) // return; //} if (string.Compare(RealFileName, saveAsFileName, true) == 0) { Save(); } else { Save(saveAsFileName, false); EditorAPI.OpenFileAsDocument(saveAsFileName, true, true); } #endif } break; case "Undo": if (undoSystem != null) { if (undoSystem.DoUndo()) { Modified = true; } } break; case "Redo": if (undoSystem != null) { if (undoSystem.DoRedo()) { Modified = true; } } break; case "Play": { var component = LoadedResource?.ResultComponent; if (component != null && RunSimulation.CheckTypeSupportedByPlayer(component.BaseType)) { if (!EditorAPI.SaveDocuments()) { return; } //if( Modified ) //{ // if( !Save( null ) ) // return; //} //!!!!не только standalone var realFileName = VirtualPathUtility.GetRealPathByVirtual(LoadedResource.Owner.Name); RunSimulation.Run(realFileName, RunSimulation.RunMethod.Player); } } break; case "Find Resource": if (!string.IsNullOrEmpty(RealFileName)) { EditorAPI.SelectFilesOrDirectoriesInMainResourcesWindow(new string[] { RealFileName }); } break; } }
bool Save(SaveOperation operation) { if (!CanSave) { return(false); } var saveOperation = Session.CreateWorkbookSaveOperation(); var savePath = Session.Workbook.LogicalPath; if (savePath.IsNull || operation == SaveOperation.SaveAs) { var saveDialog = new CommonSaveFileDialog { Title = Catalog.GetString("Save Workbook"), DefaultFileName = Session.Title, AlwaysAppendDefaultExtension = true, DefaultExtension = ".workbook" }; if (!savePath.IsNull) { saveDialog.InitialDirectory = savePath.DirectoryExists ? savePath.ParentDirectory : savePath; } saveDialog.FolderChanging += (o, e) => { if (e.Folder.EndsWith(".workbook", StringComparison.OrdinalIgnoreCase)) { e.Cancel = true; } }; saveDialog.Filters.Add(new CommonFileDialogFilter("Xamarin Workbook", ".workbook")); CommonFileDialogComboBox formatComboBox = null; if (saveOperation.SupportedOptions.HasFlag(WorkbookSaveOptions.Archive)) { formatComboBox = new CommonFileDialogComboBox(); formatComboBox.Items.Add(new CommonFileDialogComboBoxItem( Catalog.GetString("Package Directory"))); formatComboBox.Items.Add(new CommonFileDialogComboBoxItem( Catalog.GetString("Archive"))); formatComboBox.SelectedIndex = saveOperation.Options.HasFlag( WorkbookSaveOptions.Archive) ? 1 : 0; var formatGroup = new CommonFileDialogGroupBox("Workbook Format:"); formatGroup.Items.Add(formatComboBox); saveDialog.Controls.Add(formatGroup); } if (saveDialog.ShowDialog(this) != CommonFileDialogResult.Ok) { return(false); } if (formatComboBox != null) { switch (formatComboBox.SelectedIndex) { case 0: saveOperation.Options &= ~WorkbookSaveOptions.Archive; break; case 1: saveOperation.Options |= WorkbookSaveOptions.Archive; break; default: throw new IndexOutOfRangeException(); } } savePath = saveDialog.FileName; saveOperation.Destination = savePath; } var success = false; try { Session.SaveWorkbook(saveOperation); NoteRecentDocument(); success = true; IsDirty = false; } catch (Exception e) { Log.Error(TAG, e); } return(success); }
private void Purchase_Order_Save_Button_Click(object sender, RoutedEventArgs e) { if (CommonFileDialog.IsPlatformSupported) { CommonSaveFileDialog dlg = new CommonSaveFileDialog(); dlg.Title = "Save As"; dlg.DefaultExtension = "csv"; dlg.DefaultFileName = "Purchase_Order_"; dlg.InitialDirectory = Settings.Default.Last_Purchase_Order_Save_Directory; dlg.DefaultDirectory = Settings.Default.Last_Purchase_Order_Save_Directory; dlg.AddToMostRecentlyUsedList = false; dlg.EnsureFileExists = true; dlg.EnsurePathExists = true; dlg.EnsureReadOnly = false; dlg.EnsureValidNames = true; dlg.ShowPlacesList = true; if (dlg.ShowDialog() == CommonFileDialogResult.Ok) { string filePath = dlg.FileName; string extention = Path.GetExtension(filePath); if (!extention.Equals(".csv")) { filePath += ".csv"; } Settings.Default.Last_Purchase_Order_Save_Directory = filePath.Substring(0, filePath.LastIndexOf('\\')); Settings.Default.Save(); try { int rowCount = Purchase_Order_DataGrid.Items.Count; int colCount = Purchase_Order_DataGrid.Columns.Count; StringBuilder csv = new StringBuilder(); foreach (DataGridColumn dgc in Purchase_Order_DataGrid.Columns) { csv.Append(dgc.Header.ToString()).Append(','); } csv.AppendLine(); for (int row = 0; row < rowCount; row++) { for (int col = 0; col < colCount; col++) { DataGridCell cell = mainWindow.GetCell(Purchase_Order_DataGrid, mainWindow.GetRow(Purchase_Order_DataGrid, row), col); csv.Append(((TextBlock)cell.Content).Text).Append(','); } csv.AppendLine(); } File.WriteAllText(filePath, csv.ToString()); Process.Start(Settings.Default.Last_Purchase_Order_Save_Directory); } catch (IOException ex) { MessageBox.Show(ex.Message); } } Activate(); } }
private void Event1_1_Click(object sender, RoutedEventArgs e) { int index = comboBox1.SelectedIndex; string newKey = null, directory = null; using (var sfd = new CommonSaveFileDialog()) { sfd.Title = Properties.Resources.Strings["ui_0:c_1_1"][0]; sfd.InitialDirectory = conf.UserDirectory; sfd.DefaultFileName = string.Format("configuration_{0}", conf.Configurations.Count); sfd.DefaultExtension = "config"; sfd.Filters.Add(new CommonFileDialogFilter("Configuration Files", "*.config")); if (sfd.ShowDialog() == CommonFileDialogResult.Cancel) { sfd.Dispose(); return; } newKey = Path.GetFileNameWithoutExtension(sfd.FileName); directory = Path.GetDirectoryName(sfd.FileName); sfd.Dispose(); } if (directory != conf.UserDirectory) { if (QueryOnSaveChanges()) { conf.UserDirectory = directory; comboBox1.Items.Clear(); } else { return; } } Header header = new Header(newKey); header.PropertyChanged += Header_PropertyChanged; if (key1 != newKey) { key1 = newKey; conf.Configurations.Add(key1, header); conf.SetConfiguration(key1); comboBox1.Items.Add(key1); index = comboBox1.Items.Count - 1; } else { conf.Configurations[key1] = header; conf.SetConfiguration(key1); comboBox1.SelectedIndex = -1; } comboBox1.SelectedIndex = index; } // New configuration
private void ButtonGetResult_Click(object sender, RoutedEventArgs e) { var dirPath = TextBoxDirPath.Text; if (string.IsNullOrWhiteSpace(dirPath)) { MessageBox.Show(string.Format("Поле директория не может быть пустым")); } else if (!Directory.Exists(dirPath)) { MessageBox.Show(string.Format("Директория не существует! Проверте указанный путь: \"{0}\"", dirPath)); } else { try { var dialog = new CommonSaveFileDialog { InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), DefaultFileName = new DirectoryInfo(dirPath).Name, AlwaysAppendDefaultExtension = true, DefaultExtension = "txt" }; dialog.AlwaysAppendDefaultExtension = true; dialog.Filters.Add(CommonFileDialogStandardFilters.TextFiles); var result = dialog.ShowDialog(); if (result == CommonFileDialogResult.Ok) { var ignoreFolders = TextBoxIgnoreFolders.Text .Trim() .Replace("\r", String.Empty) .Replace("\n", String.Empty) .Replace(" ", String.Empty) .TrimEnd(';') .Split(';') .ToList(); var globalIgnoreFolders = TextBoxGlobalIgnorFolders.Text .Trim() .Replace("\r", String.Empty) .Replace("\n", String.Empty) .Replace(" ", String.Empty) .TrimEnd(',') .Split(',') .ToList(); var fileCounter = new FileCounter(dirPath, TextBoxFilterExt.Text, ignoreFolders, globalIgnoreFolders); var progressWindow = new ProgressWindow(fileCounter, dialog.FileName, TextBoxFileTitle.Text) { ButtonStart = { Visibility = Visibility.Hidden } }; //runs the progress operation upon window load progressWindow.ShowDialog(); } } catch (Exception ex) { MessageBox.Show(string.Format("Произошла ошибка!\r\n{0}", ex.Message)); } } }
private void ToDBButton(object sender, RoutedEventArgs e) { /*Select folder containing *.CVS files to be merged*/ CommonOpenFileDialog dialogFolder = new CommonOpenFileDialog(); dialogFolder.InitialDirectory = "C:\\Users\\jedrz\\Desktop\\VENDING\\Audyt kopia zapasowa\\1"; /*TEMP - REMOVE ME*/ dialogFolder.IsFolderPicker = true; if (dialogFolder.ShowDialog() == CommonFileDialogResult.Ok) { /*Select DB that will be updated or create a new one*/ string databasePath; bool isDatabaseNew; MessageBoxResult newDatabaseRequired = MessageBox.Show("Create new database?", "Database", MessageBoxButton.YesNoCancel); if (newDatabaseRequired == MessageBoxResult.Yes) { CommonSaveFileDialog dialogDB = new CommonSaveFileDialog(); dialogDB.Filters.Add(new CommonFileDialogFilter("SQLite Files (*.sqlite)", ".sqlite")); dialogDB.DefaultExtension = ".sqlite"; dialogDB.InitialDirectory = "C:\\Users\\jedrz\\Desktop\\VENDING\\Audyt kopia zapasowa\\1"; /*TEMP - REMOVE ME*/ if (dialogDB.ShowDialog() == CommonFileDialogResult.Ok) { databasePath = dialogDB.FileName; isDatabaseNew = true; } else { return; } } else if (newDatabaseRequired == MessageBoxResult.No) { CommonOpenFileDialog dialogDB = new CommonOpenFileDialog(); dialogDB.InitialDirectory = "C:\\Users\\jedrz\\Desktop\\VENDING\\Audyt kopia zapasowa\\1"; /*TEMP - REMOVE ME*/ dialogDB.Filters.Add(new CommonFileDialogFilter("SQLite Files (*.sqlite)", ".sqlite")); if (dialogDB.ShowDialog() == CommonFileDialogResult.Ok) { databasePath = dialogDB.FileName; isDatabaseNew = false; } else { return; } } else { return; } /*After selecting DB and folder with CVS files proceed to merging*/ FileHandling fileHandling = new FileHandling(); if (fileHandling.MergeFiles(dialogFolder.FileName, databasePath, isDatabaseNew)) { MessageBox.Show("Data added to the database.", "Success"); } else { MessageBox.Show("Failure - data was not added to the database.", "Failure"); } } }
private void Window_Loaded(object sender, RoutedEventArgs e) { if (!Directory.Exists(_temporaryDirectory)) { Directory.CreateDirectory(_temporaryDirectory); } //Clear the temporary directory foreach (var file in Directory.GetFiles(_temporaryDirectory)) { File.Delete(file); } //Add the treeview items for every drive foreach (var s in Directory.GetLogicalDrives()) { var item = new TreeViewItem { Header = GetStackpanel(s), Tag = s, FontWeight = FontWeights.Normal }; item.Items.Add(DummyNode); item.Expanded += folder_Expanded; FoldersItem.Items.Add(item); } //Adds a treeview item for the home folder: var home = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); var item2 = new TreeViewItem { Header = GetStackpanel(home), Tag = home, FontWeight = FontWeights.Normal }; item2.Items.Add(DummyNode); item2.Expanded += folder_Expanded; item2.IsSelected = true; FoldersItem.Items.Add(item2); //Checks if Zippy has command line args, and if so, it uses them: var args = Environment.GetCommandLineArgs(); if (args.Length > 1) { var path = args[1]; if (File.Exists(path)) { _type = IsArchive(path); if (_type == ArchiveTypes.None) { var parent = new FileInfo(path).Directory?.FullName; SelectFolder(parent); } else { OpenArchive(path); } } else if (Directory.Exists(path)) { var info = new DirectoryInfo(path); Zip(ArchiveTypes.Zip, null, new List <FileItem> { new FileItem(path) { IsDir = true, Path = path, Name = info.Name } }, true); } else { switch (path) { case "-e": case "-h": path = args[2]; var info = new FileInfo(path); if (IsArchive(path) != ArchiveTypes.None) { if (args[1] == "-e") { var parent = new FileInfo(path).Directory?.FullName; var dialog = new CommonOpenFileDialog { IsFolderPicker = true, InitialDirectory = parent }; var result = dialog.ShowDialog(); if (result == CommonFileDialogResult.Ok) { if (Directory.Exists(dialog.FileName)) { WriteToDirectory(ArchiveFactory.Open(path), dialog.FileName); } } } else { var toDir = info.Directory?.FullName; WriteToDirectory(ArchiveFactory.Open(path), toDir); if (toDir != null) { Process.Start(toDir); } } } break; case "-a": var saveAs = new CommonSaveFileDialog(); saveAs.Filters.Add(new CommonFileDialogFilter("Zip Archive", ".zip")); saveAs.DefaultExtension = ".zip"; var files = args.Skip(2).ToArray(); saveAs.InitialDirectory = new FileInfo(files[0]).Directory?.FullName; if (saveAs.ShowDialog() == CommonFileDialogResult.Ok) { var archive = ZipArchive.Create(); var tmp = _temporaryDirectory + "\\" + DateTime.Now.Ticks; Directory.CreateDirectory(tmp); foreach (var file in files) { if (File.Exists(file)) { File.Copy(file, Path.Combine(tmp, new FileInfo(file).Name)); } else if (Directory.Exists(file)) { DirectoryCopy(file, Path.Combine(tmp, new DirectoryInfo(file).Name)); } } archive.AddAllFromDirectory(tmp); if (File.Exists(saveAs.FileName)) { File.Delete(saveAs.FileName); } SaveTo(archive, saveAs.FileName, new WriterOptions(CompressionType.LZMA)); try { Directory.Delete(tmp, true); } catch { // TODO: error handling } } break; default: break; } } } }
/// <summary> /// Shows select file dialog. /// </summary> /// <param name="title">Title that appears in the title bar of the popup window.</param> /// <param name="selectedFile">File user selected.</param> /// <param name="filters">Filters to apply to file extensions.</param> /// <param name="defaultExtension">Default extension to apply.</param> /// <param name="path">Current path where select folder dialog will start.</param> /// <returns><code>CommonFileDialogResult</code> object indicating how user responded to the dialog.</returns> public static CommonFileDialogResult ShowSaveFileDialog(string title, out string selectedFile, IEnumerable <CommonFileDialogFilter> filters = null, string defaultExtension = null, string path = null) { var filtersList = filters as IList <CommonFileDialogFilter> ?? (filters == null ? null : filters.ToList()); if (CommonFileDialog.IsPlatformSupported) { // Display a CommonSaveFileDialog to select only files selectedFile = string.Empty; var cfd = new CommonSaveFileDialog { Title = title, EnsurePathExists = true, EnsureReadOnly = true }; if (!string.IsNullOrWhiteSpace(defaultExtension)) { cfd.DefaultExtension = defaultExtension; } else if (filtersList != null && filtersList.Any() && filtersList.First().Extensions.Count > 0) { cfd.DefaultExtension = filtersList.First().Extensions[0]; } if (!string.IsNullOrWhiteSpace(path)) { try { while (!string.IsNullOrWhiteSpace(path) && !Directory.Exists(path)) { path = Path.GetDirectoryName(path); } cfd.InitialDirectory = path; } catch (Exception e) { _log.Error(e.Message, e); } } if (filtersList != null) { foreach (var filter in filtersList) { cfd.Filters.Add(filter); } } var result = cfd.ShowDialog(); if (result == CommonFileDialogResult.Ok) { var selectedShellObject = cfd.FileAsShellObject; selectedFile = selectedShellObject.ParsingName; } return(result); } else { var fileDialog = new SaveFileDialog { RestoreDirectory = true, Title = title }; while (!string.IsNullOrWhiteSpace(path) && !Directory.Exists(path)) { fileDialog.InitialDirectory = path; } if (!string.IsNullOrWhiteSpace(defaultExtension)) { fileDialog.DefaultExt = defaultExtension; } else if (filtersList != null && filtersList.Any() && filtersList.First().Extensions.Count > 0) { fileDialog.DefaultExt = filtersList.First().Extensions[0]; } if (filtersList != null) { var sb = new StringBuilder(); foreach (var filter in filtersList) { foreach (var extension in filter.Extensions) { if (sb.Length != 0) { sb.Append("|"); } sb.AppendFormat("{0}|{1}", filter.DisplayName, extension); } } fileDialog.Filter = sb.ToString(); } var result = fileDialog.ShowDialog(); selectedFile = fileDialog.FileName; return(GetCommonFileDialogResult(result)); } }
public void File_SaveAs() { ExpressionEditor_AcceptEdit(); var defaultFileName = Handler.SourceType == ModelSourceType.Database ? "Model.bim" : File_Current; using (var fbd = new CommonSaveFileDialog()) { // Configure dialog: fbd.DefaultFileName = defaultFileName; fbd.Filters.Clear(); if (Handler.SourceType == ModelSourceType.Pbit) { fbd.Filters.Add(new CommonFileDialogFilter("Power BI Template", "*.pbit")); } fbd.Filters.Add(new CommonFileDialogFilter("Tabular Model Files", "*.bim")); fbd.Filters.Add(new CommonFileDialogFilter("All files", "*.*")); var currentSerializeOptions = Handler.FolderSerializeOptions; var specialSerializeOptions = _file_SaveMode == ModelSourceType.File && currentSerializeOptions != null && !currentSerializeOptions.Equals(SerializeOptions.DefaultFile); var useAnnotatedSerializationSettingsCheckBox = new CommonFileDialogCheckBox { Text = "Use serialization settings from annotations", IsChecked = specialSerializeOptions }; if (currentSerializeOptions != null) { fbd.Controls.Add(useAnnotatedSerializationSettingsCheckBox); } var res = fbd.ShowDialog(); if (res == CommonFileDialogResult.Ok && !string.IsNullOrWhiteSpace(fbd.FileName)) { using (new Hourglass()) { UI.StatusLabel.Text = "Saving..."; var fileType = fbd.Filters[fbd.SelectedFileTypeIndex - 1].Extensions.FirstOrDefault(); Handler.Save(fbd.FileName, fileType == "pbit" ? SaveFormat.PowerBiTemplate : SaveFormat.ModelSchemaOnly, Preferences.Current.GetSerializeOptions(false), useAnnotatedSerializationSettingsCheckBox.IsChecked); RecentFiles.Add(fbd.FileName); RecentFiles.Save(); UI.FormMain.PopulateRecentFilesList(); // If not connected to a database, change the current working file: if (Handler.SourceType != ModelSourceType.Database) { File_Current = fbd.FileName; File_SaveMode = ModelSourceType.File; } UpdateUIText(); } } } }
private void saveFileButton_Click(object sender, EventArgs e) { // Initialize detailsListView.Items.Clear(); pictureBox1.Image = null; // Show a CommonSaveFileDialog with couple of file filters. // Also show some properties (specific to the filter selected) // that the user can update from the dialog itself. CommonSaveFileDialog saveCFD = new CommonSaveFileDialog(); saveCFD.AlwaysAppendDefaultExtension = true; saveCFD.DefaultExtension = ".docx"; // When the file type changes, we will add the specific properties // to be collected from the dialog (refer to the saveCFD_FileTypeChanged event handler) saveCFD.FileTypeChanged += new EventHandler(saveCFD_FileTypeChanged); saveCFD.Filters.Add(new CommonFileDialogFilter("Word Documents", "*.docx")); saveCFD.Filters.Add(new CommonFileDialogFilter("JPEG Files", "*.jpg")); if (saveCFD.ShowDialog() == CommonFileDialogResult.Ok) { // Get the selected file (this is what we'll save...) // Save it to disk, so we can read/write properties for it // Because we can't really create a Office file or Picture file, just copying // an existing file to show the properties if (saveCFD.SelectedFileTypeIndex == 1) { File.Copy(Path.Combine(Directory.GetCurrentDirectory(), "sample files\\test.docx"), saveCFD.FileName, true); } else { File.Copy(Path.Combine(Directory.GetCurrentDirectory(), "sample files\\test.jpg"), saveCFD.FileName, true); } // Get the ShellObject for this file ShellObject selectedSO = ShellFile.FromFilePath(saveCFD.FileName); // Get the properties from the dialog (user might have updated the properties) ShellPropertyCollection propColl = saveCFD.CollectedProperties; // Write the properties on our shell object using (ShellPropertyWriter propertyWriter = selectedSO.Properties.GetPropertyWriter()) { if (propColl.Contains(SystemProperties.System.Title)) { propertyWriter.WriteProperty(SystemProperties.System.Title, propColl[SystemProperties.System.Title].ValueAsObject); } if (propColl.Contains(SystemProperties.System.Author)) { propertyWriter.WriteProperty(SystemProperties.System.Author, propColl[SystemProperties.System.Author].ValueAsObject); } if (propColl.Contains(SystemProperties.System.Keywords)) { propertyWriter.WriteProperty(SystemProperties.System.Keywords, propColl[SystemProperties.System.Keywords].ValueAsObject); } if (propColl.Contains(SystemProperties.System.Comment)) { propertyWriter.WriteProperty(SystemProperties.System.Comment, propColl[SystemProperties.System.Comment].ValueAsObject); } if (propColl.Contains(SystemProperties.System.Category)) { propertyWriter.WriteProperty(SystemProperties.System.Category, propColl[SystemProperties.System.Category].ValueAsObject); } if (propColl.Contains(SystemProperties.System.ContentStatus)) { propertyWriter.WriteProperty(SystemProperties.System.Title, propColl[SystemProperties.System.Title].ValueAsObject); } if (propColl.Contains(SystemProperties.System.Photo.DateTaken)) { propertyWriter.WriteProperty(SystemProperties.System.Photo.DateTaken, propColl[SystemProperties.System.Photo.DateTaken].ValueAsObject); } if (propColl.Contains(SystemProperties.System.Photo.CameraModel)) { propertyWriter.WriteProperty(SystemProperties.System.Photo.CameraModel, propColl[SystemProperties.System.Photo.CameraModel].ValueAsObject); } if (propColl.Contains(SystemProperties.System.Rating)) { propertyWriter.WriteProperty(SystemProperties.System.Rating, propColl[SystemProperties.System.Rating].ValueAsObject); } } currentlySelected = selectedSO; DisplayProperties(selectedSO); showChildItemsButton.Enabled = selectedSO is ShellContainer ? true : false; } }
public NewWindow() { InitializeComponent(); ResourceService.CultureChanged += OnCultureChanged; foreach (var subview in ModuleHost.Instance.SubViews) { AddOrShowView(subview, false); var menuitem = new MenuItem { Header = subview.GetTitle(ResourceService.CurrentCulture) }; menuitem.Click += (_, __) => AddOrShowView(subview, true); ResourceService.CultureChanged += (_, e) => menuitem.Header = subview.GetTitle(e.NewValue); subviews.Items.Add(menuitem); } foreach (var subwindow in ModuleHost.Instance.SubWindows) { var menuitem = new MenuItem { Header = subwindow.GetTitle(ResourceService.CurrentCulture) }; var closure = new SubWindowClosure(menuitem, subwindow); menuitem.Click += closure.Click; ResourceService.CultureChanged += closure.OnCultureChanged; switch (subwindow.Category) { case SubWindowCategory.Overview: subwindowOverview.Items.Add(menuitem); break; case SubWindowCategory.Statistics: subwindowStatistics.Items.Add(menuitem); break; case SubWindowCategory.Information: subwindowInformation.Items.Add(menuitem); break; } } ResourceService.CultureChanged += (_, __) => viewList[nameof(GameHost)].Title = StringTable.Browser; DockCommands = new Config.CommandSet { Save = new DelegateCommand(() => TrySaveLayout()), Load = new DelegateCommand(() => TryLoadLayout()), SaveAs = new DelegateCommand(() => { using (var filedialog = new CommonSaveFileDialog()) { filedialog.InitialDirectory = Environment.CurrentDirectory; filedialog.DefaultFileName = "config.xml"; filedialog.Filters.Add(new CommonFileDialogFilter("Xml Files", "*.xml")); filedialog.Filters.Add(new CommonFileDialogFilter("All Files", "*")); if (filedialog.ShowDialog() == CommonFileDialogResult.Ok) { TrySaveLayout(filedialog.FileName); } } }), LoadFrom = new DelegateCommand(() => { using (var filedialog = new CommonOpenFileDialog()) { filedialog.InitialDirectory = Environment.CurrentDirectory; filedialog.Filters.Add(new CommonFileDialogFilter("Xml Files", "*.xml")); filedialog.Filters.Add(new CommonFileDialogFilter("All Files", "*")); if (filedialog.ShowDialog() == CommonFileDialogResult.Ok) { TryLoadLayout(filedialog.FileName); } } }) }; }