private void SaveClicked(object sender, RoutedEventArgs e) { // var dialog = new Microsoft.Win32.SaveFileDialog() { AddExtension = true }; dialog.Filter = "Portable Network Graphics|*.png"; bool?result = dialog.ShowDialog(); if (result.HasValue && result.Value) { try { using (Stream stream = dialog.OpenFile()) { var encoder = new TiffBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create((BitmapSource)this.image.Source)); encoder.Save(stream); } this.Close(); } catch (SystemException ex) { MessageBox.Show("Can't save to the file. " + ex.Message, "File Error", MessageBoxButton.OK); } } }
/// <summary> /// 导出DataGrid数据到Excel为CVS文件 /// 使用utf8编码 中文是乱码 改用Unicode编码 /// /// </summary> /// <param name="withHeaders">是否带列头</param> /// <param name="grid">DataGrid</param> public static void ExportDataGridSaveAs(this System.Windows.Controls.DataGrid grid, bool withHeaders) { try { var data = ExportDataGrid(true, grid, true); var sfd = new Microsoft.Win32.SaveFileDialog { DefaultExt = "csv", Filter = "CSV Files (*.csv)|*.csv|All files (*.*)|*.*", FilterIndex = 1 }; if (sfd.ShowDialog() == true) { using (Stream stream = sfd.OpenFile()) { using (var writer = new StreamWriter(stream, System.Text.Encoding.Unicode)) { data = data.Replace(",", "\t"); writer.Write(data); writer.Close(); } stream.Close(); } } MessageBox.Show("导出成功!"); } catch (Exception ex) { Console.WriteLine(ex.Message); } }
private void Calc_Click(object sender, RoutedEventArgs e) { var dialog = new Microsoft.Win32.SaveFileDialog { Filter = "HTML Files (*.html)|*.html" }; if (dialog.ShowDialog() == true) { var comments = _loadComments.LoadComments(filePath); _buildComments.BuildComments(_heads, comments); Stream fileStream; if ((fileStream = dialog.OpenFile()) != null) { _outputService.Print(_heads, fileStream, OutputService.PrintFormats.Html); Browser.Source = new Uri(@"file:///" + dialog.FileName); FilePath.Text = $"Data Saved: {dialog.FileName}"; } else { throw new Exception(); } } }
private void Button_Click(object sender, RoutedEventArgs e) { var dlg = new Microsoft.Win32.SaveFileDialog(); dlg.Filter = "PDF files (*.pdf)|*.pdf"; //var t = dlg.ShowDialog(); if (dlg.ShowDialog().Value) { // create pdf document var pdf = new C1PdfDocument(); pdf.Landscape = true; pdf.Compression = CompressionLevel.NoCompression; // render all grids into pdf document var options = new PdfExportOptions(); options.ScaleMode = ScaleMode.ActualSize; GridExport.RenderGrid(pdf, _flex1, options); pdf.NewPage(); GridExport.RenderGrid(pdf, _flex2, options); pdf.NewPage(); GridExport.RenderGrid(pdf, _flex3, options); pdf.NewPage(); GridExport.RenderGrid(pdf, _flex4, options); // save document using (var stream = dlg.OpenFile()) { pdf.Save(stream); } } }
/// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void SaveParsed_Click(object sender, RoutedEventArgs e) { try { if (string.IsNullOrWhiteSpace(Parsed.Text)) { if (!Properties.Settings.Default.DisableErrorPopups) { MessageBox.Show(Strings.NothingParsed, Strings.Error, MessageBoxButton.OK, MessageBoxImage.Error); } return; } Microsoft.Win32.SaveFileDialog dialog = new Microsoft.Win32.SaveFileDialog { FileName = "chatlog.txt", Filter = "Text File | *.txt" }; if (dialog.ShowDialog() != true) { return; } using (StreamWriter sw = new StreamWriter(dialog.OpenFile())) { sw.Write(Parsed.Text.Replace("\n", Environment.NewLine)); } } catch { MessageBox.Show(Strings.SaveError, Strings.Error, MessageBoxButton.OK, MessageBoxImage.Error); } }
// mode: // 0 = regular // 1 = compressed // 2 = encrypted public void ExportLogsToCsv(int mode = 0) { Stream myStream; SaveFileDialog saveFileDialog1 = new SaveFileDialog(); saveFileDialog1.Filter = "csv files (*.csv)|*.csv"; saveFileDialog1.FilterIndex = 2; saveFileDialog1.RestoreDirectory = true; try { if (saveFileDialog1.ShowDialog().Value) { if ((myStream = saveFileDialog1.OpenFile()) != null) { WriteLogsToStream(mode, myStream); // Code to write the stream goes here. myStream.Close(); } } } catch (Exception ex) { Console.WriteLine("Błąd podczas zapisywania pliku: " + ex.Message); } }
private void _btnSave_Click(object sender, RoutedEventArgs e) { var dlg = new Microsoft.Win32.SaveFileDialog(); dlg.DefaultExt = ".csv"; dlg.Filter = "Comma Separated Values (*.csv)|*.csv|" + "Plain text (*.txt)|*.txt|" + "HTML (*.html)|*.html"; if (dlg.ShowDialog() == true) { // select format based on file extension var fileFormat = FileFormat.Csv; switch (System.IO.Path.GetExtension(dlg.SafeFileName).ToLower()) { case ".htm": case ".html": fileFormat = FileFormat.Html; break; case ".txt": fileFormat = FileFormat.Text; break; } // save the file using (var stream = dlg.OpenFile()) { _flex.Save(stream, fileFormat); } } }
private void Export_Click(object sender, RoutedEventArgs e) { // Configure save file dialog box Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog(); dlg.FileName = "TableData"; // Default file name dlg.DefaultExt = ".text"; // Default file extension dlg.Filter = "Text documents (.txt)|*.txt"; // Filter files by extension // Show save file dialog box Nullable <bool> result = dlg.ShowDialog(); string theData = ""; for (int i = 1; i < TableListBox.Items.Count; i++) { theData += TableListBox.Items[i]; theData += "\n"; } // Process save file dialog box results if (result == true) { // Save document string filename = dlg.FileName; using (Stream sw = (Stream)dlg.OpenFile()) { byte[] data = (new UTF8Encoding(true)).GetBytes(theData); sw.Write(data, 0, data.Length); sw.Close(); } } }
private void Export(object param) { var grid = param as RadGridView; var dialog = new SaveFileDialog() { DefaultExt = this.SelectedExportFormat, Filter = String.Format("(*.{0})|*.{1}", this.SelectedExportFormat, this.SelectedExportFormat) }; if (dialog.ShowDialog() == true) { using (var stream = dialog.OpenFile()) { switch (this.SelectedExportFormat) { case "xlsx": grid.ExportToXlsx(stream); break; case "pdf": grid.ExportToPdf(stream); break; } } } }
private void ExportDefaultStyles(object param) { var grid = param as RadGridView; var exportOptions = new GridViewDocumentExportOptions() { ExportDefaultStyles = true, ShowColumnFooters = grid.ShowColumnFooters, ShowColumnHeaders = grid.ShowColumnHeaders, ShowGroupFooters = grid.ShowGroupFooters }; var dialog = new SaveFileDialog() { DefaultExt = this.SelectedExportFormat, Filter = String.Format("(*.{0})|*.{1}", this.SelectedExportFormat, this.SelectedExportFormat) }; if (dialog.ShowDialog() == true) { using (var stream = dialog.OpenFile()) { switch (this.SelectedExportFormat) { case "xlsx": grid.ExportToXlsx(stream, exportOptions); break; case "pdf": grid.ExportToPdf(stream, exportOptions); break; } } } }
public string _FileName;// = "C:\\programming\\MKIO_wpf\\myfile.data"; public void SaveData(object sender, RoutedEventArgs e) { Constant.ConstantFunc.writeToLog("Нажата кнопка сохранения фильтра"); Stream myStream; Microsoft.Win32.SaveFileDialog mySave = new Microsoft.Win32.SaveFileDialog(); mySave.InitialDirectory = Constant.Constants.defaultFilterPath; mySave.Filter = "Data files (*.filter)|*.filter|All files (*.*)|*.*"; mySave.RestoreDirectory = true; if (mySave.ShowDialog() == true) { if ((myStream = mySave.OpenFile()) != null) { //_FileName = (string)myStream;// Code to write the stream goes here. using (var writer = new StreamWriter(myStream)) { var xs = new XmlSerializer(typeof(ObservableCollection <TestDataViewModel>)); xs.Serialize(writer, DataSource.Data); } myStream.Close(); nameOfFilter = mySave.SafeFileName.Replace(".filter", ""); Constant.ConstantFunc.writeToLog("Сохранение фильтра прошло успешно"); } } }
private void btnSave_Click(object sender, RoutedEventArgs e) { var dialog = new Microsoft.Win32.SaveFileDialog(); dialog.Filter = "Rich Text File (*.psql)|*.psql|All Files (*.*)|*.*"; dialog.FileName = "PRDB_Query.psql"; //set initial filename if (dialog.ShowDialog() == true) { foreach (TabItem tabItem in TbQry.Items) { if (tabItem.IsSelected) { using (var stream = dialog.OpenFile()) { RichTextBox richTextBox = (RichTextBox)tabItem.Content; var range = new TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd); range.Save(stream, DataFormats.Text); var name = dialog.FileName; int index = name.LastIndexOf(@"\"); tabItem.Header = name.Substring(index + 1, name.Length - index - 1); } break; } } } }
private async void ExecuteSaveDocumentCommand(object o) { var saveDialog = new Microsoft.Win32.SaveFileDialog(); saveDialog.Filter = "TakoDeploy Document (*.tdd)|*.tdd|All files (*.*)|*.*"; var result = saveDialog.ShowDialog(); if (!result.HasValue || (result.HasValue && !result.Value)) { return; } var name = saveDialog.SafeFileName; if (!name.EndsWith(".tdd")) { name += ".tdd"; } //using (var streaem = new MemoryStream()) using (var stream = new System.IO.StreamWriter(saveDialog.OpenFile())) { var data = Newtonsoft.Json.Linq.JObject.FromObject(DocumentManager.Current.Deployment); stream.Write(data.ToString()); DocumentManager.Current.CurrentFileName = saveDialog.SafeFileName; } //DocumentManager.Save(); }
private void Button_Click(object sender, RoutedEventArgs e) { Microsoft.Win32.SaveFileDialog SavAll = new Microsoft.Win32.SaveFileDialog(); SavAll.FileName = "KeySaveMMMMKKKKK"; SavAll.Filter = "Text Files | *.txt"; SavAll.DefaultExt = "txt"; SavAll.InitialDirectory = @"c:\"; if (SavAll.ShowDialog() == true) { using (StreamWriter sw = new StreamWriter(SavAll.OpenFile())) { if (TxtB1.Text != "") { sw.Write($"{System.IO.Path.GetFileName(TxtB1.Text)} Key : "); sw.WriteLine(Key1.Text); } if (TxtB2.Text != "") { sw.Write($"{System.IO.Path.GetFileName(TxtB2.Text)} Key : "); sw.WriteLine(Key2.Text); } if (TxtB3.Text != "") { sw.Write($"{System.IO.Path.GetFileName(TxtB3.Text)} Key : "); sw.WriteLine(Key3.Text); } } } }
private void SaveAs_Click(object sender, RoutedEventArgs e) { if (!MVM.CanSaveFile) { return; } var Dialog = new Microsoft.Win32.SaveFileDialog { DefaultExt = ".sav", Filter = "Fortnite ClientSettings (*.sav)|*.sav" }; var Result = Dialog.ShowDialog(); if (!Result.HasValue || !Result.Value) { return; } try { using (var Settings = Dialog.OpenFile()) { if (SaveToStream(Settings)) { OpenFilePath = Dialog.FileName; } } } catch { MessageBox.Show("Failed to save file.", "Error", MessageBoxButton.OK, MessageBoxImage.Error); } }
private void Button_Click(object sender, RoutedEventArgs e) { var dlg = new Microsoft.Win32.SaveFileDialog(); dlg.Filter = "PDF files (*.pdf)|*.pdf"; //var t = dlg.ShowDialog(); if (dlg.ShowDialog().Value) { // create pdf document var pdf = new C1PdfDocument(); pdf.Landscape = true; pdf.Compression = CompressionLevel.NoCompression; // render all grids into pdf document var options = new PdfExportOptions(); options.ScaleMode = ScaleMode.ActualSize; GridExport.RenderGrid(pdf, _flex1, options); pdf.NewPage(); GridExport.RenderGrid(pdf, _flex2, options); pdf.NewPage(); GridExport.RenderGrid(pdf, _flex3, options); pdf.NewPage(); GridExport.RenderGrid(pdf, _flex4, options); // save document using (var stream = dlg.OpenFile()) { pdf.Save(stream); } } }
private void btnExport_Click(object sender, RoutedEventArgs e) { string extension = "xlsx"; Microsoft.Win32.SaveFileDialog dialog = new Microsoft.Win32.SaveFileDialog() { DefaultExt = extension, Filter = String.Format("{1} files (.{0})|.{0}|All files (.)|.", extension, "Excel"), FilterIndex = 1 }; if (dialog.ShowDialog() == true) { using (Stream stream = dialog.OpenFile()) { gridView.ExportToXlsx(stream, new GridViewDocumentExportOptions() { ShowColumnFooters = true, ShowColumnHeaders = true, ShowGroupFooters = true }); } } }
private async void saveFile(object sender, RoutedEventArgs e) { System.IO.Stream fs; Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog() { FileName = "shopList", DefaultExt = ".slt", Filter = "Shop List file | *.slt", InitialDirectory = Properties.Settings.Default.SaveDirectory }; if (dlg.ShowDialog() == true) { if ((fs = dlg.OpenFile()) != null) { Properties.Settings.Default.SaveDirectory = System.IO.Path.GetDirectoryName(dlg.FileName); Properties.Settings.Default.Save(); byte[] header = new byte[] { 0x18, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; byte[] buffer = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; List <byte> items = header.ToList(); foreach (Item item in listboxout) { string hex = item.Key.Substring(4); items.Add(Convert.ToByte(int.Parse(hex.Substring(2), System.Globalization.NumberStyles.HexNumber))); items.Add(Convert.ToByte(int.Parse(hex.Substring(0, 2), System.Globalization.NumberStyles.HexNumber))); items.AddRange(buffer); } byte[] output = items.ToArray(); await fs.WriteAsync(output, 0, output.Length); fs.Close(); } } }
/// <summary> /// creates a mesh from the current volume and tries to save it to a file /// </summary> /// <param name="volume">the volume</param> /// <param name="pkdp">the data package the mesh origined from</param> /// <param name="flipAxes">should achses be flipped?</param> static void exportMesh(ColorReconstruction volume, KinectDataPackage pkdp, bool flipAxes) { ColorMesh mesh = volume.CalculateMesh(1); Microsoft.Win32.SaveFileDialog dialog = new Microsoft.Win32.SaveFileDialog(); dialog.FileName = "KinectFusionMesh_" + pkdp.usedConfig.name + DateTime.UtcNow.ToShortDateString() + ".stl"; dialog.Filter = "STL Mesh Files|*.stl|All Files|*.*"; if (true == dialog.ShowDialog()) { using (BinaryWriter writer = new BinaryWriter(dialog.OpenFile())) { if (null == mesh || null == writer) { return; } var vertices = mesh.GetVertices(); var normals = mesh.GetNormals(); var indices = mesh.GetTriangleIndexes(); // Check mesh arguments if (0 == vertices.Count || 0 != vertices.Count % 3 || vertices.Count != indices.Count) { throw new Exception("Invalid Mesh Arguments"); } char[] header = new char[80]; writer.Write(header); // Write number of triangles int triangles = vertices.Count / 3; writer.Write(triangles); // Sequentially write the normal, 3 vertices of the triangle and attribute, for each triangle for (int i = 0; i < triangles; i++) { // Write normal var normal = normals[i * 3]; writer.Write(normal.X); writer.Write(flipAxes ? -normal.Y : normal.Y); writer.Write(flipAxes ? -normal.Z : normal.Z); // Write vertices for (int j = 0; j < 3; j++) { var vertex = vertices[(i * 3) + j]; writer.Write(vertex.X); writer.Write(flipAxes ? -vertex.Y : vertex.Y); writer.Write(flipAxes ? -vertex.Z : vertex.Z); } ushort attribute = 0; writer.Write(attribute); } } } }
public void Execute(ViewModel viewModel) { viewModel.Status = string.Empty; var request = new ScanRequest() { DeviceId = viewModel.Scanner.Device.DeviceId, Settings = new ScannerSettings { PageSize = PageSizes.Letter, ColorDepth = ColorDepths.Color, Orientation = Orientations.Portrait, Resolution = Resolutions.R300, UseAutomaticDocumentFeeder = true } }; IScanner proxy = DiscoveryHelper.CreateDiscoveryProxy(); try { var response = proxy.Scan(request); Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog(); dlg.FileName = "Document"; dlg.DefaultExt = ".pdf"; dlg.Filter = "Acrobat|*.pdf"; var result = dlg.ShowDialog(); if (result == true) { using (var file = dlg.OpenFile()) { CopyStream(response, file); } } } catch (FaultException<ScanError> e) { viewModel.Status = e.Detail.ErrorMessage; } catch (CommunicationException) { } finally { ICommunicationObject comm = ((ICommunicationObject)proxy); if (comm.State == CommunicationState.Faulted) { comm.Abort(); } else { comm.Close(); } } }
public static void ExportToImage(FrameworkElement surface) { Size size = new Size(surface.ActualWidth, surface.ActualHeight); RenderTargetBitmap renderBitmap = new RenderTargetBitmap((int)size.Width, (int)size.Height, 96d, 96d, PixelFormats.Pbgra32); renderBitmap.Render(surface); Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog(); dlg.FileName = DateTime.Now.ToString("yyyy-M-d-H_m_s"); string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\WLANFolder"; if (!Directory.Exists(path)) Directory.CreateDirectory(path); dlg.InitialDirectory = path; dlg.OverwritePrompt = true; dlg.Filter = "JPEG Image|*.jpg|Bitmap Image|*.bmp|PNG Image|*.png"; dlg.Title = "Save an Image File"; dlg.ShowDialog(); dlg.RestoreDirectory = true; if (dlg.FileName != "") { try { using(FileStream outStream = (System.IO.FileStream)dlg.OpenFile()) { switch (dlg.FilterIndex) { case 1: { JpegBitmapEncoder encoder = new JpegBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(renderBitmap)); encoder.Save(outStream); } break; case 2: { BmpBitmapEncoder encoder = new BmpBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(renderBitmap)); encoder.Save(outStream); } break; case 3: { PngBitmapEncoder encoder = new PngBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(renderBitmap)); encoder.Save(outStream); } break; default: break; } System.Diagnostics.Process.Start(dlg.FileName); } } catch (ArgumentException) { return; } } }
Stream OpenFileWrite() { var dialog = new Microsoft.Win32.SaveFileDialog(); if (dialog.ShowDialog() == true) { return(dialog.OpenFile()); } return(null); }
//Adds a card to the set. private void AddCard(object obj) { try { //Checks if there are words to add. if (FirstWord == "" || FirstWord == null || SecondWord == null || SecondWord == "") { return; } //Checks if there is no file path. if (string.IsNullOrEmpty(_filePath)) //if not... { Directory.CreateDirectory(_folderPath); //Create a new directory if not already created. //Creates save dialog box that allows user to name and save the file they are going to write to. var saveDialog = new Microsoft.Win32.SaveFileDialog(); saveDialog.InitialDirectory = @"C:\Flashcards\"; saveDialog.Filter = "Text Document(*.txt)|*.txt"; saveDialog.Title = "Card Set Name"; bool?result = saveDialog.ShowDialog(); if (!(bool)result) { return; } //Creates the file. if (saveDialog.FileName != "") //As long the file has a name... { // Saves the File via a FileStream created by the OpenFile method. _filePath = saveDialog.FileName; System.IO.FileStream fileStream = (System.IO.FileStream)saveDialog.OpenFile(); fileStream.Close(); //Can use StreamWriter to write onto files. } } //Writes to files using StreamWriter, taking the filepath as parameter. using (System.IO.StreamWriter file = new System.IO.StreamWriter(_filePath, true)) { file.WriteLine(FirstWord + ";" + SecondWord); //Writes the words into file. } //Resets the variables. FirstWord = ""; SecondWord = ""; //User Feedback. CardStatus = "Added!"; } catch (NullReferenceException e) { Debug.WriteLine("File Does Not Exist."); CardStatus = "Not Added"; return; } }
private static Stream SaveDialog(string initFileName, string fileExt = ".fdw", string filter = "Free Draw Save (*.fdw)|*fdw") { var dialog = new Microsoft.Win32.SaveFileDialog() { DefaultExt = fileExt, Filter = filter, FileName = initFileName, InitialDirectory = Directory.GetCurrentDirectory() + "Save" }; return(dialog.ShowDialog() == true?dialog.OpenFile() : Stream.Null); }
private void SaveConditions(object sender, RoutedEventArgs e) { Microsoft.Win32.SaveFileDialog saveFileDialog1 = new Microsoft.Win32.SaveFileDialog(); saveFileDialog1.Filter = "All files (*.*)|*.*"; if (saveFileDialog1.ShowDialog() == true) { BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(saveFileDialog1.OpenFile(), conditions); } }
public void SaveImage() { var dialog = new Microsoft.Win32.SaveFileDialog(); if (dialog.ShowDialog() != true) { LogPanel.Log("Canceled."); return; } var stream = dialog.OpenFile(); image.ToBitmapSource().Save(stream); LogPanel.Log($"Saved as {dialog.FileName}"); }
private void MenuItem_SaveExсel_Click(object sender, RoutedEventArgs e) { ExcelApp = new Excel.Application(); ExcelApp.Visible = true; ExcelApp.SheetsInNewWorkbook = 1; ExcelApp.Workbooks.Add(); ExcelWorksheet = ExcelApp.Workbooks[1].Worksheets.Item[1]; var itemsCount = reservations.Count; ExcelWorksheet.Range["A1"].Value = "Время"; ExcelWorksheet.Range["B1"].Value = "Дата"; ExcelWorksheet.Range["C1"].Value = "Мастер"; ExcelWorksheet.Range["D1"].Value = "Услуга"; ExcelWorksheet.Range["E1"].Value = "Клиент"; ExcelWorksheet.Range["F1"].Value = "Контактный номер"; for (var i = 0; i < itemsCount; i++) { ExcelWorksheet.Cells[i + 2, 1].Value = reservations[i].ReservationTime; ExcelWorksheet.Cells[i + 2, 2].Value = reservations[i].ReservationDateTime.Date; ExcelWorksheet.Cells[i + 2, 3].Value = reservations[i].MakeupArtist; ExcelWorksheet.Cells[i + 2, 4].Value = reservations[i].Services; ExcelWorksheet.Cells[i + 2, 5].Value = reservations[i].ClientName; ExcelWorksheet.Cells[i + 2, 6].Value = reservations[i].PhoneNumber; } ExcelWorksheet.Cells[itemsCount + 3, 1].Value = "Диспетчер"; ExcelWorksheet.Cells[itemsCount + 3, 2].Value = ActiveUser.Login; ExcelWorksheet.Cells[itemsCount + 4, 1].Value = "Сохранено"; ExcelWorksheet.Cells[itemsCount + 4, 2].Value = DateTime.Now.ToString(); ExcelWorksheet.Columns.AutoFit(); try { Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog { DefaultExt = ".xlsx", Filter = "Файлы записей в формате Excel|*.xlsx", FileName = "Таблица Excel" }; dlg.ShowDialog(); using (var fileStream = dlg.OpenFile()) { ExcelApp.Workbooks[1].SaveAs(fileStream); } } catch (Exception) { } }
private void BtnStartClick(object sender, RoutedEventArgs e) { List<string> validEmails; List<string> inValidEmails; SeleniumDriver.Program.Run(_eMails, out validEmails, out inValidEmails); // Configure save file dialog box var dlg = new Microsoft.Win32.SaveFileDialog { FileName = "ValidEmails.txt", Filter = "Text File | *.txt" }; // Show save file dialog box var result = dlg.ShowDialog(); // Process save file dialog box results if (result == true) { var writer = new StreamWriter(dlg.OpenFile()); foreach (var email in validEmails) { writer.WriteLine(email); } writer.Dispose(); writer.Close(); } // Configure save file dialog box dlg = new Microsoft.Win32.SaveFileDialog { FileName = "InValidEmails.txt", Filter = "Text File | *.txt" }; // Show save file dialog box result = dlg.ShowDialog(); // Process save file dialog box results if (result == true) { var writer = new StreamWriter(dlg.OpenFile()); foreach (var email in inValidEmails) { writer.WriteLine(email); } writer.Dispose(); writer.Close(); } }
void _btnSave_Click(object sender, RoutedEventArgs e) { var dlg = new Microsoft.Win32.SaveFileDialog(); dlg.DefaultExt = "xlsx"; dlg.Filter = "Excel Workbook (*.xlsx)|*.xlsx|" + "Excel 97-2003 Workbook (*.xls)|*.xls|" + "HTML File (*.htm;*.html)|*.htm;*.html|" + "Comma Separated Values (*.csv)|*.csv|" + "Text File (*.txt)|*.txt|" + "PDF (*.pdf)|*.pdf"; if (dlg.ShowDialog().Value) { using (var s = dlg.OpenFile()) { // dlg.FilterIndex is not working properly (SL bug) so we check // the file extension to chose the proper save format. var ext = System.IO.Path.GetExtension(dlg.SafeFileName).ToLower(); switch (ext) { case ".htm": case ".html": _flex.Save(s, FileFormat.Html, SaveOptions.Formatted); break; case ".csv": _flex.Save(s, FileFormat.Csv, SaveOptions.Formatted); break; case ".txt": _flex.Save(s, FileFormat.Text, SaveOptions.Formatted); break; case ".pdf": SavePdf(s, "ComponentOne ExcelBook"); break; case ".xlsx": _flex.SaveXlsx(s); break; default: _flex.SaveXls(s); break; } } } }
private void saveScenario() { // Prepare Scenario for saving Scenario sc = new Scenario(false); sc.Updated = DateTime.Now; sc.Author = ScenarioAuthor; sc.Name = ScenarioName; sc.Description = ScenarioDescription; for (int i = 0; i < Steps.Count; i++) { // Set metadata for saving Steps [i].Step.IPositionX = Steps [i].Left; Steps [i].Step.IPositionY = Steps [i].Top; // And add to the main Scenario stack sc.Steps.Add(Steps [i].Step); } // Initiate IO stream, show Save File dialog to select file destination Stream s; Microsoft.Win32.SaveFileDialog dlgSave = new Microsoft.Win32.SaveFileDialog(); dlgSave.Filter = "Infirmary Integrated simulation files (*.ii)|*.ii|All files (*.*)|*.*"; dlgSave.FilterIndex = 1; dlgSave.RestoreDirectory = true; if (dlgSave.ShowDialog() == true) { if ((s = dlgSave.OpenFile()) != null) { // Save in II:T1 format StringBuilder sb = new StringBuilder(); sb.AppendLine("> Begin: Scenario"); sb.Append(sc.Save()); sb.AppendLine("> End: Scenario"); StreamWriter sw = new StreamWriter(s); sw.WriteLine(".ii:t1"); // Metadata (type 1 savefile) sw.WriteLine(Encryption.HashSHA256(sb.ToString().Trim())); // Hash for validation sw.Write(Encryption.EncryptAES(sb.ToString().Trim())); // Savefile data encrypted with AES sw.Close(); s.Close(); } } }
private void button_Copy_Click(object sender, RoutedEventArgs e) { DataBaseForStudents d1 = new DataBaseForStudents(textBox_FIO.Text, textBox_Age.Text, comboBox_fak.Text, comboBox_direction.Text, Convert.ToInt32(textBox_course.Text), comboBox_expirience.Text); XmlSerializer formatter = new XmlSerializer(typeof(DataBaseForStudents)); Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog(); dlg.DefaultExt = ".xml"; dlg.Filter = "Студенты|*.xml"; dlg.FileName = "Студент №"; dlg.ShowDialog(); Stream myStream = dlg.OpenFile(); formatter.Serialize(myStream, d1); myStream.Close(); }
private void SaveFile(object sender, RoutedEventArgs e) { var dialog = new Microsoft.Win32.SaveFileDialog(); dialog.Filter = "Text File(*txt)|*.txt|Allfile(*.*)|*.*"; dialog.FileName = "File.txt"; if (dialog.ShowDialog() == true) { using (var stream = dialog.OpenFile()) { var range = new TextRange(RTBeditor.Document.ContentStart, RTBeditor.Document.ContentEnd); range.Save(stream, DataFormats.Text); } } }
private void Button_Save_Click(object sender, RoutedEventArgs e) { Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog { DefaultExt = ".xml", Filter = "Файлы записей|*.xml", FileName = "Записи" }; dlg.ShowDialog(); using (var fileStream = dlg.OpenFile()) { serializer.Serialize(fileStream, reservations.ToArray()); } }
public static void SaveAsPng(RenderTargetBitmap src) { Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog(); dlg.Filter = "PNG Files | *.png"; dlg.DefaultExt = "png"; if (dlg.ShowDialog() == true) { PngBitmapEncoder encoder = new PngBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(src)); using (var stream = dlg.OpenFile()) { encoder.Save(stream); } } }
public static void Export(object columns, IEnumerable data, ExportType type = ExportType.Xls) { Microsoft.Win32.SaveFileDialog fileDialog = new Microsoft.Win32.SaveFileDialog(); fileDialog.Filter = type == ExportType.Xls ? "(*.xls)|*.xls" : "(*.*)|*.*"; fileDialog.FileName = "data_" + DateTime.Now.ToString("yyyyMMddHHmmss"); if (fileDialog.ShowDialog() == true) { using (var stream = fileDialog.OpenFile()) { var cols = GetDataColumns(columns); if (cols != null) DoExport(stream, cols, data, type); else DoExport(stream, data, type); } //TODO: open the folder of the file var dialog = new ExportResultDialog(fileDialog.FileName); dialog.Owner = Window.GetWindow(Application.Current.MainWindow); dialog.ShowDialog(); } }
private void GuardarComoMenuItem_Click(object sender, RoutedEventArgs e) { Microsoft.Win32.SaveFileDialog sdlg = new Microsoft.Win32.SaveFileDialog(); sdlg.Filter = "Text File (*.txt)|*.txt|Show All Files (*.*)|*.*"; sdlg.FileName = "Untitled"; sdlg.Title = "Save As"; Nullable<bool> result = sdlg.ShowDialog(); if (result == true) { using (var stream = sdlg.OpenFile()) { var range = new TextRange(richTextBox1.Document.ContentStart, richTextBox1.Document.ContentEnd); range.Save(stream, DataFormats.Rtf); } } }
public void Save(MemoryStream data, string FileName) { // the actionscript API will show the dialog after the user event // has returned, so we must mimic it here 1.AtDelay( delegate { var s = new Microsoft.Win32.SaveFileDialog(); s.FileName = FileName; if (s.ShowDialog() ?? false) { using (var w = s.OpenFile()) { var a = data.ToArray(); w.Write(a, 0, a.Length); } } } ); }
private void SaveClicked(object sender, RoutedEventArgs e) { // var dialog = new Microsoft.Win32.SaveFileDialog() { AddExtension = true }; dialog.Filter = "Portable Network Graphics|*.png"; bool? result = dialog.ShowDialog(); if (result.HasValue && result.Value) { try { using(Stream stream = dialog.OpenFile()) { var encoder = new TiffBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create((BitmapSource)this.image.Source)); encoder.Save(stream); } this.Close(); } catch(SystemException ex) { MessageBox.Show("Can't save to the file. " + ex.Message, "File Error", MessageBoxButton.OK); } } }
void _btnSave_Click(object sender, RoutedEventArgs e) { var dlg = new Microsoft.Win32.SaveFileDialog(); dlg.DefaultExt = "xlsx"; dlg.Filter = "Excel Workbook (*.xlsx)|*.xlsx|" + "HTML File (*.htm;*.html)|*.htm;*.html|" + "Comma Separated Values (*.csv)|*.csv|" + "Text File (*.txt)|*.txt|" + "PDF (*.pdf)|*.pdf"; if (dlg.ShowDialog().Value) { using (var s = dlg.OpenFile()) { // dlg.FilterIndex is not working properly (SL bug) so we check // the file extension to chose the proper save format. var ext = System.IO.Path.GetExtension(dlg.SafeFileName).ToLower(); switch (ext) { case ".htm": case ".html": _flex.Save(s, FileFormat.Html, SaveOptions.Formatted); break; case ".csv": _flex.Save(s, FileFormat.Csv, SaveOptions.Formatted); break; case ".txt": _flex.Save(s, FileFormat.Text, SaveOptions.Formatted); break; case ".pdf": SavePdf(s, "ComponentOne ExcelBook"); break; case ".xlsx": default: _flex.SaveXlsx(s); break; } } } }
private void ExportToExcel() { //if (System.Windows.Interop.BrowserInteropHelper.IsBrowserHosted) //{ //MessageBox.Show("Due to restricted user-access permissions, this feature cannot be demonstrated when the Live Explorer is running as an XBAP browser application. Please download the full Xceed DataGrid for WPF package and run the Live Explorer as a desktop application to try out this feature.", "Feature unavailable"); //return; //} // The simplest way to export in Excel format is to call the // DataGridControl.ExportToExcel() method. However, if you want to specify export // settings, you have to take the longer, more descriptive and flexible route: // the ExcelExporter class. // excelExporter.FixedColumnCount will automatically be set to the specified // grid's FixedColumnCount value. //ExcelExporter excelExporter = new ExcelExporter(this.GridDetails); //excelExporter.ExportStatFunctionsAsFormulas = this.exportStatFunctionsAsFormulasCheckBox.IsChecked.GetValueOrDefault(); //excelExporter.IncludeColumnHeaders = this.includeColumnHeadersCheckBox.IsChecked.GetValueOrDefault(); //excelExporter.IsHeaderFixed = this.isHeaderFixedCheckBox.IsChecked.GetValueOrDefault(); //excelExporter.RepeatParentData = this.repeatParentDataCheckBox.IsChecked.GetValueOrDefault(); //excelExporter.DetailDepth = Convert.ToInt32(this.detailDepthTextBox.Value); //excelExporter.StatFunctionDepth = Convert.ToInt32(this.statFunctionDepthTextBox.Value); //excelExporter.UseFieldNamesInHeader = this.UseFieldNamesInHeaderCheckBox.IsChecked.GetValueOrDefault(); Microsoft.Win32.SaveFileDialog saveFileDialog = new Microsoft.Win32.SaveFileDialog(); saveFileDialog.Filter = "XML Spreadsheet (*.xml)|*.xml|All files (*.*)|*.*"; try { if (saveFileDialog.ShowDialog().GetValueOrDefault()) { using (Stream stream = saveFileDialog.OpenFile()) { //excelExporter.Export(stream); GridDetails.ExportToExcel(stream); } } } catch { } }
private void ExportToCsv() { //if (System.Windows.Interop.BrowserInteropHelper.IsBrowserHosted) //{ //MessageBox.Show("Due to restricted user-access permissions, this feature cannot be demonstrated when the Live Explorer is running as an XBAP browser application. Please download the full Xceed DataGrid for WPF package and run the Live Explorer as a desktop application to try out this feature.", "Feature unavailable"); //return; //} // The simplest way to export in CSV format is to call the // DataGridControl.ExportToCsv() method. However, if you want to specify export // settings, you have to take the longer, more descriptive and flexible route: // the CsvExporter class. CsvExporter csvExporter = new CsvExporter(this.GridDetails); // By setting the Culture to the CurrentCulture (system culture by default), the // date and number formats set in the regional settings will be used. csvExporter.FormatSettings.Culture = CultureInfo.CurrentCulture; csvExporter.FormatSettings.DateTimeFormat = (string)this.dateTimeFormatComboBox.SelectedValue; csvExporter.FormatSettings.NumericFormat = (string)this.numberFormatComboBox.SelectedValue; csvExporter.FormatSettings.Separator = (char)this.separatorComboBox.SelectedValue; csvExporter.FormatSettings.TextQualifier = (char)this.textQualifierComboBox.SelectedValue; csvExporter.IncludeColumnHeaders = this.includeColumnHeadersCheckBox.IsChecked.GetValueOrDefault(); csvExporter.RepeatParentData = this.repeatParentDataCheckBox.IsChecked.GetValueOrDefault(); csvExporter.DetailDepth = Convert.ToInt32(this.detailDepthTextBox.Value); csvExporter.UseFieldNamesInHeader = this.UseFieldNamesInHeaderCheckBox.IsChecked.GetValueOrDefault(); Microsoft.Win32.SaveFileDialog saveFileDialog = new Microsoft.Win32.SaveFileDialog(); saveFileDialog.Filter = "CSV file (*.csv)|*.csv|Text file (*.txt)|*.txt|All files (*.*)|*.*"; try { if (saveFileDialog.ShowDialog().GetValueOrDefault()) { using (Stream stream = saveFileDialog.OpenFile()) { csvExporter.Export(stream); } } } catch { } }
void backgroundWorker_DoWork(object sender, DoWorkEventArgs e) { Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog(); dlg.FileName = download_file.ToString(); dlg.Filter = "All files (*.*)|*.*"; double progress; if (dlg.ShowDialog() == true) { try { FtpWebRequest request = (FtpWebRequest)WebRequest.Create(MainWindow.address + MainWindow.directory + MainWindow.fileToDownload); request.Credentials = new NetworkCredential(MainWindow.c_username, MainWindow.c_password); request.Method = WebRequestMethods.Ftp.GetFileSize; request.Proxy = null; long fileSize; // this is the key for ReportProgress using (WebResponse resp = request.GetResponse()) fileSize = resp.ContentLength; request = (FtpWebRequest)WebRequest.Create(MainWindow.address + MainWindow.directory + MainWindow.fileToDownload); request.Credentials = new NetworkCredential(MainWindow.c_username, MainWindow.c_password); request.Method = WebRequestMethods.Ftp.DownloadFile; FtpWebResponse responseFileDownload = (FtpWebResponse)request.GetResponse(); Stream responseStream = responseFileDownload.GetResponseStream(); FileStream writeStream = (System.IO.FileStream)dlg.OpenFile(); int Length = 1024; Byte[] buffer = new Byte[Length]; int bytesRead = 0; int bytes = 0; do { writeStream.Write(buffer, 0, bytesRead); bytesRead = responseStream.Read(buffer, 0, Length); // totalReadBytesCount += bytesRead; bytes += bytesRead; progress = bytes * 100.0 / fileSize; // don't forget to increment bytesRead ! // int totalSize = (int)(fileSize) / 1000; // Kbytes backgroundWorker.ReportProgress((int)progress); } while (bytesRead != 0); writeStream.Close(); responseStream.Close(); } catch { MessageBox.Show("Download fail"); } finally { } } }
private void OnExportMenuItemClick( object sender, RoutedEventArgs e ) { Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog(); dlg.Title = "Export Configuration"; AssignCommonFileDialogProps( dlg ); if( dlg.ShowDialog() != true ) return; try { _windowData.Document.Save( dlg.OpenFile(), WidgetDocSaveFormat.Xml ); } catch( Exception ex ) { ReportToUserApplicationError( ex, "There were issues exporting configuration." ); } }
void annotationCanvas_SaveAnnotation(Obany.Render.Objects.Canvas canvas, string mimeType) { _progressControl = new ProgressControl(); AddWatermark(canvas); string files = CultureHelper.GetString(Properties.Resources.ResourceManager, "FILES"); string allFiles = CultureHelper.GetString(Properties.Resources.ResourceManager, "ALLFILES"); string ext = ""; string filter = ""; if (mimeType == "image/jpeg") { ext += ".jpg"; filter = "Jpg " + files + " (*.jpg)|*.jpg"; _progressControl.Status = CultureHelper.GetString(Properties.Resources.ResourceManager, "CREATING") + " Jpg"; } else if (mimeType == "application/vnd.ms-xpsdocument") { ext += ".xps"; filter = "Xps " + files + " (*.xps)|*.xps"; _progressControl.Status = CultureHelper.GetString(Properties.Resources.ResourceManager, "CREATING") + " Xps"; } else if (mimeType == "application/pdf") { ext += ".pdf"; filter = "Pdf " + files + " (*.pdf)|*.pdf"; _progressControl.Status = CultureHelper.GetString(Properties.Resources.ResourceManager, "CREATING") + " Pdf"; } filter += "|" + allFiles + " (*.*)|*.*"; #if SILVERLIGHT SaveFileDialog saveFileDialog = new SaveFileDialog(); #else Microsoft.Win32.SaveFileDialog saveFileDialog = new Microsoft.Win32.SaveFileDialog(); if (!string.IsNullOrEmpty(_lastSavePath)) { saveFileDialog.InitialDirectory = _lastSavePath; } #endif saveFileDialog.DefaultExt = ext; saveFileDialog.Filter = filter; if (saveFileDialog.ShowDialog().Value) { #if !SILVERLIGHT _lastSavePath = System.IO.Path.GetDirectoryName(saveFileDialog.FileName); #endif System.IO.Stream saveStream = saveFileDialog.OpenFile(); DialogPanel.ShowDialog(Properties.Resources.ResourceManager, "PROGRESS", _progressControl, "buttonCancel", DialogButtons.Cancel, delegate(DialogResult dialogControlResult) { _progressControl = null; } ); _saveTaskId = Guid.NewGuid(); _coreLogic.AnnotationSave(_saveTaskId, saveStream, canvas, mimeType, delegate(bool success, Guid saveTaskIdComplete) { Action a = delegate() { if (_saveTaskId == saveTaskIdComplete) { if (!success) { DialogPanel.ShowInformationBox(CultureHelper.GetString(Properties.Resources.ResourceManager, "ANNOTATIONUNABLETOSAVE"), DialogButtons.Ok, null); } else { if (annotationCanvas != null) { annotationCanvas.ResetChanges(); } } if (_progressControl != null) { DialogPanel.Close(_progressControl, DialogResult.Close); } _saveTaskId = Guid.Empty; } }; #if SILVERLIGHT Dispatcher.BeginInvoke(a); #else Dispatcher.Invoke(a); #endif }); } }
internal void ExportCourseToExcel(Course selectedCourse) { //TODO: refactor so we don't use dialogs in viewmodels Microsoft.Win32.SaveFileDialog saveFileDialog1 = new Microsoft.Win32.SaveFileDialog(); saveFileDialog1.OverwritePrompt = true; saveFileDialog1.RestoreDirectory = true; saveFileDialog1.DefaultExt = "xslx"; // Adds a extension if the user does not saveFileDialog1.AddExtension = true; saveFileDialog1.InitialDirectory = Convert.ToString(Environment.SpecialFolder.MyDocuments); saveFileDialog1.Filter = "Excel Spreadsheet|*.xlsx"; saveFileDialog1.FileName = string.Format("Exported Notes for {0} - {1}.xlsx", selectedCourse.Name, DateTime.Now.ToString("dd-MM-yyyy HH.mm.ss")); saveFileDialog1.Title = "Save Exported Notes"; if (saveFileDialog1.ShowDialog() == true) { try { using (System.IO.FileStream fs = (System.IO.FileStream)saveFileDialog1.OpenFile()) { XslsExporter exporter = new XslsExporter(); exporter.CreateSpreadsheet(fs, selectedCourse.Tracks.ToList(), selectedCourse.Notes.ToList()); fs.Close(); } var openResult = System.Windows.MessageBox.Show(System.Windows.Application.Current.MainWindow, "Export successful! Would you like to open the file?", "Open exported file confirmation", System.Windows.MessageBoxButton.YesNo); if (openResult == System.Windows.MessageBoxResult.Yes) { System.Diagnostics.ProcessStartInfo info = new System.Diagnostics.ProcessStartInfo(); info.WindowStyle = System.Diagnostics.ProcessWindowStyle.Maximized; info.FileName = saveFileDialog1.FileName; var process = System.Diagnostics.Process.Start(info); } } catch (Exception e) { System.Windows.MessageBox.Show(System.Windows.Application.Current.MainWindow, "Error exporting :( - " + e.ToString()); } } }
//More tab save button private void button1_Click(object sender, RoutedEventArgs e) { this.Cursor = Cursors.AppStarting; button2.IsEnabled = false; Microsoft.Win32.SaveFileDialog SaveFileDialog1 = new Microsoft.Win32.SaveFileDialog(); SaveFileDialog1.Filter = "txt files (*.txt)|*.txt"; if ((bool)SaveFileDialog1.ShowDialog()) { using (System.IO.StreamWriter StreamWriter1 = new System.IO.StreamWriter(SaveFileDialog1.OpenFile())) { StreamWriter1.WriteLine("\n:::::::::::::::::{0}::::::::::::::::::", comboBox1.SelectedItem.ToString()); StreamWriter1.WriteLine(textBox5.Text); StreamWriter1.Close(); } MessageBox.Show("File saved successfully", "System Information", MessageBoxButton.OK, MessageBoxImage.Information); } this.Cursor = Cursors.Arrow; button2.IsEnabled = true; }
private void _btnSave_Click(object sender, RoutedEventArgs e) { var dlg = new Microsoft.Win32.SaveFileDialog(); dlg.DefaultExt = ".csv"; dlg.Filter = "Comma Separated Values (*.csv)|*.csv|" + "Plain text (*.txt)|*.txt|" + "HTML (*.html)|*.html"; if (dlg.ShowDialog() == true) { // select format based on file extension var fileFormat = FileFormat.Csv; switch (System.IO.Path.GetExtension(dlg.SafeFileName).ToLower()) { case ".htm": case ".html": fileFormat = FileFormat.Html; break; case ".txt": fileFormat = FileFormat.Text; break; } // save the file using (var stream = dlg.OpenFile()) { _flex.Save(stream, fileFormat); } } }
private void SaveFile() { if (Files.SelectedItem != null) { List<Documents> D = new List<Documents>(); foreach (Documents d in Files.SelectedItems) { D.Add(d); } D.All(a => { Microsoft.Win32.SaveFileDialog sfd = new Microsoft.Win32.SaveFileDialog(); sfd.OverwritePrompt = true; sfd.FileName = a.Name; sfd.ValidateNames = true; sfd.AddExtension = true; sfd.Filter = "文档|*.doc;*docx;*.pdf|电子表格|*.xls;*.xlsx|图片|*.jpg;*.gif;*.png;*.jpge|所有支持的文件类型|*.doc;*docx;*.pdf;*.xls;*.xlsx;*.jpg;*.gif;*.png;*.jpge"; sfd.FilterIndex = 4; sfd.Title = String.Format("另存为——{0}", a.Name); if ((bool)sfd.ShowDialog(this)) { System.IO.Stream output = sfd.OpenFile(); output.BeginWrite(a.Data, 0, a.Data.Length, new AsyncCallback((b) => { output.Close(); }), null); return true; } return false; }); } statusText.Content = "请先选择一个要下载的文件。"; }
protected virtual void Save(String path, Visifire.Charts.ExportType exportType, Boolean showDilog) { if (_saveIconImage != null) { _saveIconImage.Visibility = Visibility.Collapsed; _toolTip.Hide(); _toolbarContainer.UpdateLayout(); } #if SL try { WriteableBitmap bitmap = new WriteableBitmap(this, null); #if !WP if (bitmap != null) { SaveFileDialog saveDlg = new SaveFileDialog(); saveDlg.Filter = "JPEG (*.jpg)|*.jpg|BMP (*.bmp)|*.bmp"; saveDlg.DefaultExt = ".jpg"; if ((bool)saveDlg.ShowDialog()) { using (Stream fs = saveDlg.OpenFile()) { String[] filename = saveDlg.SafeFileName.Split('.'); String fileExt; if (filename.Length >= 2) { fileExt = filename[filename.Length - 1]; exportType = (Visifire.Charts.ExportType)Enum.Parse(typeof(Visifire.Charts.ExportType), fileExt, true); } else exportType = Visifire.Charts.ExportType.Jpg; MemoryStream stream = Graphics.GetImageStream(bitmap, exportType); // Get Bytes from memory stream and write into IO stream byte[] binaryData = new Byte[stream.Length]; long bytesRead = stream.Read(binaryData, 0, (int)stream.Length); fs.Write(binaryData, 0, binaryData.Length); } } } #endif } catch (Exception ex) { if (_saveIconImage != null) { _saveIconImage.Visibility = Visibility.Visible; } System.Diagnostics.Debug.WriteLine("Note: Please make sure that Height and Width of the chart is set properly."); System.Diagnostics.Debug.WriteLine(ex.Message); } #else // Matrix m = PresentationSource.FromVisual(Application.Current.MainWindow).CompositionTarget.TransformToDevice; // double dx = m.M11* 96; // double dy = m.M22 * 96; // Save current canvas transform Transform transform = this.LayoutTransform; // reset current transform (in case it is scaled or rotated) _rootElement.LayoutTransform = null; // Create a render bitmap and push the surface to it RenderTargetBitmap renderBitmap = new RenderTargetBitmap( (int)(this.ActualWidth), (int)(this.ActualHeight), 96d, 96d, PixelFormats.Pbgra32); renderBitmap.Render(_rootElement); if (showDilog) { Microsoft.Win32.SaveFileDialog saveDlg = new Microsoft.Win32.SaveFileDialog(); saveDlg.Filter = "Jpg Files (*.jpg)|*.jpg|BMP Files (*.bmp)|*.bmp"; saveDlg.DefaultExt = ".jpg"; if ((bool)saveDlg.ShowDialog()) { BitmapEncoder encoder; if (saveDlg.FilterIndex == 2) encoder = new BmpBitmapEncoder(); else encoder = new JpegBitmapEncoder(); using (Stream fs = saveDlg.OpenFile()) { encoder.Frames.Add(BitmapFrame.Create(renderBitmap)); // save the data to the stream encoder.Save(fs); } } } else { path = System.IO.Path.GetFullPath(path.Trim()); String fileName = System.IO.Path.GetFileName(path); if (String.IsNullOrEmpty(fileName)) { fileName = "VisifireChart"; path += fileName; } switch (exportType) { case Visifire.Charts.ExportType.Bmp: path += ".bmp"; break; default: path += ".jpg"; break; } FileStream outStream; // Create a file stream for saving image using (outStream = new FileStream(path, FileMode.Create)) { BitmapEncoder encoder; switch (exportType) { case Visifire.Charts.ExportType.Bmp: encoder = new BmpBitmapEncoder(); break; default: encoder = new JpegBitmapEncoder(); break; } // push the rendered bitmap to it encoder.Frames.Add(BitmapFrame.Create(renderBitmap)); // save the data to the stream encoder.Save(outStream); } if (outStream == null) throw new System.IO.IOException("Unable to export the chart to an image as the specified path is invalid."); } // Restore previously saved layout _rootElement.LayoutTransform = transform; #endif if (_saveIconImage != null && ToolBarEnabled) _saveIconImage.Visibility = Visibility.Visible; }
//Save saveButton private void button2_Click(object sender, RoutedEventArgs e) { this.Cursor = Cursors.AppStarting; button2.IsEnabled = false; progressBar1.Value = 0; Microsoft.Win32.SaveFileDialog SaveFileDialog1 = new Microsoft.Win32.SaveFileDialog(); SaveFileDialog1.Filter = "txt files (*.txt)|*.txt"; if ((bool)SaveFileDialog1.ShowDialog()) { using (System.IO.StreamWriter StreamWriter1 = new System.IO.StreamWriter(SaveFileDialog1.OpenFile())) { if (radioButton1.IsChecked == true) { int i = 0; foreach (string stringWin32class in stringWin32classes) { StreamWriter1.WriteLine("\n:::::::::::::::::{0}::::::::::::::::::", stringWin32class); StreamWriter1.WriteLine(DeviceInformation(stringWin32class)); progressBar1.Value = (++i * 100 / 443); } StreamWriter1.Close(); } else { int intIncrement=0,intCount = 0; foreach (CheckBox CheckBox1 in listBox1.Items) { if (CheckBox1.IsChecked == true) { intCount++; } } foreach (CheckBox CheckBox1 in listBox1.Items) { if (CheckBox1.IsChecked == true) { StreamWriter1.WriteLine("\n:::::::::::::::::{0}::::::::::::::::::", CheckBox1.Content.ToString()); StreamWriter1.WriteLine(DeviceInformation(CheckBox1.Content.ToString())); intIncrement++; progressBar1.Value = (intIncrement * 100 / intCount); MessageBox.Show(intIncrement.ToString()); MessageBox.Show(progressBar1.Value.ToString()); } } StreamWriter1.Close(); } MessageBoxResult result = MessageBox.Show("File saved successfully", "System Information", MessageBoxButton.OK, MessageBoxImage.Information); } } progressBar1.Value = 0; this.Cursor = Cursors.Arrow; button2.IsEnabled = true; }
public void Execute(object parameter) { Microsoft.Win32.SaveFileDialog sfd = new Microsoft.Win32.SaveFileDialog(); sfd.OverwritePrompt = true; sfd.CheckPathExists = true; sfd.ValidateNames = true; if (sfd.ShowDialog() != true) return; using (System.IO.Stream s = sfd.OpenFile()) { var list = vm.Rules.Where(x => x.Key < int.MaxValue - 1).Select(x => new Models.Data.Xml.XmlSerializableDictionary<int, ProxyRule>.LocalKeyValuePair(x.Key, x.Value)).ToList(); System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(list.GetType()); xs.Serialize(s, list); } }
/// <summary> /// 导出DataGrid数据到Excel为CVS文件 /// 使用utf8编码 中文是乱码 改用Unicode编码 /// /// </summary> /// <param name="withHeaders">是否带列头</param> /// <param name="grid">DataGrid</param> public static void ExportDataGridSaveAs(bool withHeaders, System.Windows.Controls.DataGrid grid) { try { string data = ExportDataGrid(true, grid, true); var sfd = new Microsoft.Win32.SaveFileDialog { DefaultExt = "csv", Filter = "CSV Files (*.csv)|*.csv|All files (*.*)|*.*", FilterIndex = 1 }; if (sfd.ShowDialog() == true) { using (Stream stream = sfd.OpenFile()) { using (var writer = new StreamWriter(stream, System.Text.Encoding.Unicode)) { data = data.Replace(",", "\t"); writer.Write(data); writer.Close(); } stream.Close(); } } MessageBox.Show("导出成功!"); } catch (Exception ex) { //LogHelper.Error(ex); } }
public override void Run(GraphController ctrl) { System.IO.Stream myStream; var saveFileDialog1 = new Microsoft.Win32.SaveFileDialog(); saveFileDialog1.Filter = "Altaxo graph files (*.axogrp)|*.axogrp|All files (*.*)|*.*"; saveFileDialog1.FilterIndex = 1; saveFileDialog1.RestoreDirectory = true; if (true == saveFileDialog1.ShowDialog((System.Windows.Window)Current.Workbench.ViewObject)) { if ((myStream = saveFileDialog1.OpenFile()) != null) { Altaxo.Serialization.Xml.XmlStreamSerializationInfo info = new Altaxo.Serialization.Xml.XmlStreamSerializationInfo(); info.BeginWriting(myStream); info.AddValue("Graph", ctrl.Doc); info.EndWriting(); myStream.Close(); } } }