private void btnAdd_Click(object sender, RoutedEventArgs e) { bool? result = null; OpenFileDialog fileDlg = new OpenFileDialog(); fileDlg.Filter = "Dynamic Linked Libraries|*.dll"; fileDlg.Title = "Add Plugin Assembly..."; fileDlg.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); result = fileDlg.ShowDialog(this); if (result != null && result == true) { if (ValidateAndAddAssembly(fileDlg.FileName)) { // Notify the user of the impending restart MessageBox.Show(this, "The application must now restart to ensure the Plugin is fully functional.", "Plugin Added!", MessageBoxButton.OK, MessageBoxImage.Information); // Restart try { Process.Start(Application.ResourceAssembly.Location); Application.Current.Shutdown(); } catch (Exception ex) { PluginManager.log.Error("An exception was thrown while attempting to restart the application as a result of a plugin removal.", ex); } } } }
private void BrowseButton_Click(object sender, RoutedEventArgs e) { // Create OpenFileDialog Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog(); // Set filter for file extension and default file extension dlg.DefaultExt = def; dlg.Filter = fil; // Display OpenFileDialog by calling ShowDialog method Nullable<bool> result = dlg.ShowDialog(); // Get the selected file name and display in a TextBox if (result == true) { if (dlg.FileName.Length > 0) { SelectedFileTextBox.Text = dlg.FileName; location = String.Concat(System.IO.Path.GetDirectoryName(dlg.FileName), "\\", System.IO.Path.GetFileNameWithoutExtension(dlg.FileName), ".xps"); // Set DocumentViewer.Document to XPS document if (txtTitle.Text.Trim().Length == 0) { String title = dlg.SafeFileName; txtTitle.Text = title.Substring(0, title.Length - 4); } btnCreate.IsEnabled = true; } } }
private void OnLoadModule(object sender, System.Windows.RoutedEventArgs e) { OpenFileDialog dialog = new OpenFileDialog() { CheckFileExists = true, Filter = "Binary Files (*.bin, *.exe, *.img, *.iso, *.o)|*.bin;*.exe;*.img;*.iso;*.o|" + "All Files (*.*)|*.*|Image Files (*.img, *.iso)|*.img;*.iso|" + "Object Files (*.bin, *.o, *.exe)|*.bin;*.o;*.exe", FilterIndex = 0, Title = "Select Debug Binary", Multiselect = true, }; bool? result = dialog.ShowDialog(this); if (result.HasValue && result.Value) { foreach (string modulePath in dialog.FileNames) { try { Loader.LoadImage(modulePath, null); } catch (Exception x) { var msg = String.Format("An error occured and the module '{0}' " + "has not been loaded:\n{1}", modulePath, x.ToString()); MessageBox.Show(msg, "Error Loading Module", MessageBoxButton.OK, MessageBoxImage.Error); } } this.RefreshItems(); } }
public void Merge() { var openDialog = new OpenFileDialog() { Filter = "firesec2 files|*.fscp", DefaultExt = "firesec2 files|*.fscp" }; if (openDialog.ShowDialog().Value) { ServiceFactory.Events.GetEvent<ConfigurationClosedEvent>().Publish(null); ZipConfigActualizeHelper.Actualize(openDialog.FileName, false); var folderName = AppDataFolderHelper.GetLocalFolder("Administrator/MergeConfiguration"); var configFileName = Path.Combine(folderName, "Config.fscp"); if (Directory.Exists(folderName)) Directory.Delete(folderName, true); Directory.CreateDirectory(folderName); File.Copy(openDialog.FileName, configFileName); LoadFromZipFile(configFileName); ServiceFactory.ContentService.Invalidate(); FiresecManager.UpdateConfiguration(); ServiceFactory.Events.GetEvent<ConfigurationChangedEvent>().Publish(null); ServiceFactory.Layout.Close(); if (ApplicationService.Modules.Any(x => x.Name == "Устройства, Зоны, Направления")) ServiceFactory.Events.GetEvent<ShowDeviceEvent>().Publish(Guid.Empty); else if (ApplicationService.Modules.Any(x => x.Name == "Групповой контроллер")) ServiceFactory.Events.GetEvent<ShowXDeviceEvent>().Publish(Guid.Empty); ServiceFactory.SaveService.FSChanged = true; ServiceFactory.SaveService.PlansChanged = true; ServiceFactory.SaveService.GKChanged = true; ServiceFactory.Layout.ShowFooter(null); } }
private void bOpen_Click(object sender, RoutedEventArgs e) { var dialog = new OpenFileDialog(); if (dialog.ShowDialog() == true) { var lines = System.IO.File.ReadAllLines(dialog.FileName); FuncList.Clear(); foreach (var line in lines) { if (line.StartsWith("Engine") || line.StartsWith("-----")) continue; var arr = line.Split(new[]{' ','\t','\r'}, StringSplitOptions.RemoveEmptyEntries); if (arr.Length == 8) { var data = new CompareData { Engine = arr[0], Function1 = arr[1], Function2 = arr[2], Address1 = arr[3], Address2 = arr[4], CRC = arr[5], CRC1 = arr[6], CRC2 = arr[7], }; if (!data.Function2.StartsWith("sub_")) FuncList.Add(data); } } } }
/// <summary> /// Initializes a new instance of the IntroductionViewModel class. /// </summary> public HomeViewModel(IConfigurationService configurationService) { _configurationService = configurationService; selectedFile = _configurationService.IsFileLoaded() ? "hi" : ""; CreateNewFileCommand = new RelayCommand(() => { var saveFileDialog = new SaveFileDialog(); saveFileDialog.AddExtension = true; saveFileDialog.DefaultExt = "pktd"; saveFileDialog.Filter = "Parakeet File|*.pktd;*.pkd"; saveFileDialog.FileOk += SaveFileDialog_FileOk; saveFileDialog.ShowDialog(); }, () => string.IsNullOrEmpty(SelectedFile)); OpenExistingFileCommand = new RelayCommand(() => { var openFileDialog = new OpenFileDialog(); openFileDialog.AddExtension = true; openFileDialog.DefaultExt = "pktd"; openFileDialog.Filter = "Parakeet File|*.pktd;*.pkd"; openFileDialog.Multiselect = false; openFileDialog.FileOk += OpenFileDialog_FileOk; openFileDialog.ShowDialog(); }, () => string.IsNullOrEmpty(SelectedFile)); }
public void LoadImage() { var filedialog = new OpenFileDialog() { Multiselect = false }; if (filedialog.ShowDialog() == true) { var temp = File.ReadAllBytes(filedialog.FileName); var newtemp = new ushort[0x10000]; for (int i = 0; i < temp.Length; i++) { if (i % 2 == 0) { newtemp[i / 2] |= (ushort)(temp[i] << 8); } else { newtemp[i / 2] |= (ushort)(temp[i]); } } App.CPU.SetMemory(newtemp); } }
public static async Task ShowHsNotInstalledMessage(this MetroWindow window) { var settings = new MetroDialogSettings {AffirmativeButtonText = "Ok", NegativeButtonText = "Select manually"}; var result = await window.ShowMessageAsync("Hearthstone install directory not found", "Hearthstone Deck Tracker will not work properly if Hearthstone is not installed on your machine (obviously).", MessageDialogStyle.AffirmativeAndNegative, settings); if(result == MessageDialogResult.Negative) { var dialog = new OpenFileDialog { Title = "Select Hearthstone.exe", DefaultExt = "Hearthstone.exe", Filter = "Hearthstone.exe|Hearthstone.exe" }; var dialogResult = dialog.ShowDialog(); if(dialogResult == true) { Config.Instance.HearthstoneDirectory = Path.GetDirectoryName(dialog.FileName); Config.Save(); Helper.MainWindow.ShowMessage("Restart required.", "Please restart HDT for this to take effect."); } } }
public static string OpenTest(string courseName_copy, string groupName_copy, string testName_copy) { OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog.Filter = "TST Files (*.tst) |*.tst"; Nullable<bool> resultOfDialog = openFileDialog.ShowDialog(); string resultOfParsing; _courseName = courseName_copy; _groupName = groupName_copy; _testName = testName_copy; if (resultOfDialog == true) { string pathOfTest = openFileDialog.FileName; SelectDirectoryPath(pathOfTest); try { resultOfParsing = TestParser.Instance.ParseTest(pathOfTest, folderPath); } catch(Exception) { resultOfParsing = "Wystąpił problem podczas odczytu plik"; } if(resultOfParsing == "Ok") { ZipDirectory(folderPath, fileName); if(IS_OK == true) unzipTest(); } return resultOfParsing; } return ""; }
private void OpenCommand_Execute(object sender, ExecutedRoutedEventArgs e) { OpenFileDialog ofd = new OpenFileDialog(); if (ofd.ShowDialog() == true) { ellipses.Clear(); StreamReader sr = new StreamReader(ofd.FileName); while (!sr.EndOfStream) { String[] g = sr.ReadLine().Split(' '); Circle circle = new Circle() { R = double.Parse(g[0]), X = double.Parse(g[1]), Y = double.Parse(g[2]) }; ellipses.Add(circle); } sr.Close(); vd = new VD<Circle, DeloneCircle>(ellipses[0], ellipses[1], null); for (int i = 2; i < ellipses.Count; i++) vd.Insert(ellipses[i]); if (vd != null) BuildTriples(vd.NextTriple(vd.NullTriple), gg_triples, true); else gg_triples.Children.Clear(); triple = vd.NextTriple(vd.NullTriple); } }
private void Button_Click_1(object sender, RoutedEventArgs e) { OpenFileDialog openFileDialog1 = new OpenFileDialog(); const string initialDirectory = "g:\\temp\\"; if (Directory.Exists(initialDirectory)) openFileDialog1.InitialDirectory = initialDirectory; openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"; openFileDialog1.FilterIndex = 2; openFileDialog1.RestoreDirectory = true; if (openFileDialog1.ShowDialog() == true) { var result = LogParser.Parse(openFileDialog1.FileName); _battles = LogParser.DivideIntoBattlesAndApplyGuards(result); ListBattles.Items.Clear(); ListBattles.BeginInit(); foreach (var battle in _battles) { ListBattles.Items.Add(battle.ToString()); } ListBattles.EndInit(); } }
/// <inheritdoc/> public async Task<string> GetImageKeyAsync() { try { var dlg = new OpenFileDialog() { Filter = "All (*.*)|*.*", FilterIndex = 0, FileName = "" }; if (dlg.ShowDialog(_serviceProvider.GetService<MainWindow>()) == true) { var path = dlg.FileName; var bytes = System.IO.File.ReadAllBytes(path); var key = _serviceProvider.GetService<ProjectEditor>().Project.AddImageFromFile(path, bytes); return await Task.Run(() => key); } } catch (Exception ex) { _serviceProvider.GetService<ILog>().LogError($"{ex.Message}{Environment.NewLine}{ex.StackTrace}"); } return null; }
public override InteriorField[,] GetLayout() { OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog.DefaultExt = "txt"; DirectoryInfo currentDir = new DirectoryInfo(Environment.CurrentDirectory); openFileDialog.InitialDirectory = (currentDir.EnumerateDirectories().FirstOrDefault(d => d.Name == DataSubdirName) ?? currentDir).FullName; if (openFileDialog.ShowDialog().GetValueOrDefault()) { this.LayoutIdentifier = openFileDialog.FileName; using (StreamReader readLines = new StreamReader(openFileDialog.OpenFile())) { List<List<InteriorField>> layout = readLines .ReadToEnd() .Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries) .Select(s => s .Select(c => this.CreateField(c)).ToList()).ToList(); int columnsCount = layout.Max(l => l.Count); InteriorField[,] result = new InteriorField[layout.Count, columnsCount]; for (int row = 0; row < layout.Count; row++) { for (int col = 0; col < layout[row].Count; col++) { result[row, col] = layout[row][col]; } } return result; } } else { return null; } }
public string ShowOpenFileDialog() { var dlg = new OpenFileDialog(); if (dlg.ShowDialog() == true) return dlg.FileName; return null; }
private void AddLanguageFile_OnClick(object sender, RoutedEventArgs e) { // Configure open file dialog box. OpenFileDialog dlg = new OpenFileDialog { DefaultExt = ".txt", Filter = "Language Files (.txt)|*.txt" }; // Show open file dialog box. bool? result = dlg.ShowDialog(); // Process open file dialog box results if (result != true) { return; } // Show language name dialog box. TextBoxWindow textboxDlg = new TextBoxWindow(); result = textboxDlg.ShowDialog("Add Language", "Please enter the name of the language!"); if (result != true) { return; } // Add language file to project. ProjectSettings projectSettings = (ProjectSettings)this.DataContext; LanguageFile languageFile = new LanguageFile { LanguageTag = textboxDlg.Text, Path = dlg.FileName }; projectSettings.AddLanguageFile(languageFile); // Refresh list. this.LanguageFileList.Items.Refresh(); }
private void NewOutputFormatMenuItem_Click(object sender, RoutedEventArgs e) { ClearCanvas(); var newOutputFormatOpenFileDialog = new OpenFileDialog { Filter = "dll files (*.dll)|*.dll", DefaultExt = ".dll", Title = "Please select dll file" }; if (newOutputFormatOpenFileDialog.ShowDialog() == true) { string pathToCopy = Path.Combine(AssemblyPath, @"Printers\", Path.GetFileName(newOutputFormatOpenFileDialog.FileName)); try { File.Copy(newOutputFormatOpenFileDialog.FileName, pathToCopy, true); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error); return; } MessageBox.Show("Printer added successfully!", "Information", MessageBoxButton.OK, MessageBoxImage.Information); } }
public override void Execute() { // Ask the user to select a file. var dlg = new OpenFileDialog(); bool? result = dlg.ShowDialog(); // If the user pressed Cancel, don't continue. if (!result.HasValue || !result.Value) { this.Result.IsSuccessful = false; this.Result.MessageTitle = "User Cancelled"; this.Result.MessageText = "The user cancelled the operation."; this.Result.MessageDetails = "Even more details can go here."; return; } // Now we'll create a new StudyUnit with the same name of that // file. Of course, if the file contained some interesting // information, we could process the file and set that information // as part of our new object. var myStudy = new StudyUnit(); myStudy.DublinCoreMetadata.Title.Current = Path.GetFileNameWithoutExtension(dlg.FileName); // Add any new items to a collection, and use the Api object // to tell Designer about them. var newItems = new Collection<IVersionable>(); newItems.Add(myStudy); this.Api.Import(newItems, true); // Add the new item to the ModifiedItems of the Result property, // to let Colectica know that you created something new. this.Result.ModifiedItems.Add(myStudy); }
private void OpenCommandHandler(object sender, RoutedEventArgs e) { OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog(); dlg.FileName = "Document"; // Default file name dlg.DefaultExt = ".txt"; // Default file extension dlg.Filter = "Text documents (.txt)|*.txt"; // Filter files by extension // Show open file dialog box Nullable<bool> result = dlg.ShowDialog(); // Process open file dialog box results if (result == true) { // Open document string filename = dlg.FileName; TextRange range; FileStream fStream; if (File.Exists(filename)) { tabControl1.SelectedIndex = 1; range = new TextRange(rtb1.Document.ContentStart, rtb1.Document.ContentEnd); fStream = new FileStream(filename, FileMode.OpenOrCreate); range.Load(fStream, DataFormats.Text); fStream.Close(); } FormatWholeDocument(); } }
public void ImportaSentencas() { //List<string> mensagemLinha = new List<string>(); OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog.Title = ""; openFileDialog.InitialDirectory = @"c:\temp"; openFileDialog.Filter = "Arquivos texto (*.txt)|*.txt| All files (*.*)|*.*"; openFileDialog.FilterIndex = 2; openFileDialog.RestoreDirectory = true; if (openFileDialog.ShowDialog() == true) arquivo = openFileDialog.FileName; if (String.IsNullOrEmpty(arquivo)) { MessageBox.Show("Arquivo Invalido", "Alerta", MessageBoxButton.OK); } else { using (StreamReader texto = new StreamReader(arquivo)) { while ((mensagem = texto.ReadLine()) != null) { //mensagemLinha.Add(mensagem); CadastroSentenca.Adiciona(new Sentenca(0, mensagem, (bool)rbtn100.IsChecked)); } } } Atualizar(); }
protected override void OnStartup(StartupEventArgs e) { OpenFileDialog dialog = new OpenFileDialog(); Nullable<bool> result = dialog.ShowDialog(); if (result != true) { Shutdown(); return; } MachineType machineType; FileInfo fileInfo = new FileInfo(dialog.FileName); try { using (FileStream filestream = fileInfo.Open(FileMode.Open, FileAccess.Read)) { machineType = ReadMachineType(filestream); } } catch (PEHeaderNotFoundException error) { MessageBox.Show(error.Message); Shutdown(); return; } DisplayMachineType(machineType); Shutdown(); }
public void ExecuteOpenFileDialog() { var dialog = new OpenFileDialog { InitialDirectory = _defaultPath }; dialog.ShowDialog(); SelectedPath = dialog.FileName; }
private void ButtonBase_OnClick(object sender, RoutedEventArgs e) { OpenFileDialog ofd = new OpenFileDialog(); ofd.ShowDialog(); string file = ofd.FileName; SendCommand(File.ReadAllText(file)); }
void Browse() { var dialog = new OpenFileDialog(); if (dialog.ShowDialog() ?? false) { SvcUtilPath = dialog.FileName; } }
/// <summary> /// vykonávacia logika príkazu /// </summary> /// <param name="parameter">parameter príkazu</param> public void Execute(object parameter) { if (((MainWindowViewModel)parameter).HadProject == true) { string messageText = "Nemôžu byť otvorené dva projekty súčasne. Vymazať projekt?"; string messageCaption = "Vymazať projekt"; MessageBoxResult res = MessageBox.Show(messageText, messageCaption, MessageBoxButton.YesNoCancel, MessageBoxImage.Question, MessageBoxResult.Cancel); if (res == MessageBoxResult.Yes) { OpenFileDialog dialog = new OpenFileDialog(); dialog.Filter = "XML documents (.xml)|*.xml"; if (dialog.ShowDialog() == true) { string filename = dialog.FileName; ((MainWindowViewModel)parameter).Load(filename); } } ((MainWindow)Application.Current.MainWindow).mainFrame.Navigate(new Uri("Views/Pages/WelcomePage.xaml", UriKind.Relative)); } else { OpenFileDialog dialog = new OpenFileDialog(); dialog.Filter = "XML documents (.xml)|*.xml"; if (dialog.ShowDialog() == true) { string filename = dialog.FileName; ((MainWindowViewModel)parameter).Load(filename); } ((MainWindowViewModel)parameter).HadProject = true; } }
public static MEFile OpenFile() { string content = ""; // Create OpenFileDialog OpenFileDialog dlg = new OpenFileDialog(); // Set filter for file extension and default file extension dlg.DefaultExt = ".txt"; dlg.Filter = TextFileFilter; // Display OpenFileDialog by calling ShowDialog method bool? result = dlg.ShowDialog(); // Get the selected file name and display in a TextBox if (result == true) { content = File.ReadAllText(dlg.FileName); string FileName = Path.GetFileNameWithoutExtension(dlg.SafeFileName); string Extension = Path.GetExtension(dlg.SafeFileName); return new MEFile(FileName, Extension, content, dlg.FileName); } else { return MEFile.ERROR_ME_FILE; } throw new NotImplementedException(); }
private void _vmSaveFileInteractionEvent(object sender, InteractionRequestedEventArgs e) { SaveFileConfirmation _confirmation = e.Context as SaveFileConfirmation; if (_confirmation == null) return; string _msg = $"Click Yes to save configuration to {_confirmation.FilePath}, No to slecet new file, Cancel to cancel"; //switch (MessageBox.Show(_confirmation.Title, _msg, MessageBoxButton.YesNoCancel, MessageBoxImage.Question, MessageBoxResult.Cancel)) switch (MessageBox.Show(_msg, _confirmation.Title, MessageBoxButton.YesNoCancel, MessageBoxImage.Question, MessageBoxResult.Cancel)) { case MessageBoxResult.None: case MessageBoxResult.OK: case MessageBoxResult.Yes: break; case MessageBoxResult.Cancel: _confirmation.FilePath = string.Empty; break; case MessageBoxResult.No: OpenFileDialog _dialog = new OpenFileDialog() { AddExtension = true, CheckPathExists = true, DefaultExt = ".xml", Filter = "Configuration (.xml)|*.xml", FileName = _confirmation.FilePath, Title = "Save file as ..", CheckFileExists = false, ValidateNames = true, }; _confirmation.FilePath = _dialog.ShowDialog().GetValueOrDefault(false) ? _dialog.FileName : string.Empty; e.Callback(); break; default: break; } }
public OpenFileResult OpenFile(string customFilter, bool multiselect) { List<string> baseFilters = new List<string>(); if (!string.IsNullOrEmpty(customFilter)) { baseFilters.Add(customFilter); } baseFilters.Add(Resources.Translations.FilterAllSupported); baseFilters.Add(Resources.Translations.FilterAllFiles); string delimiter = "|"; string filter = baseFilters.Aggregate((i, j) => i + delimiter + j); OpenFileDialog dialog = new OpenFileDialog(); dialog.Filter = filter; dialog.FilterIndex = 1; dialog.Multiselect = multiselect; List<OpenedFile> openedFiles = new List<OpenedFile>(); if (dialog.ShowDialog() == true) { string[] fileNames = dialog.FileNames; foreach (var filePath in fileNames) { string fileName = Path.GetFileName(filePath); Stream stream = File.OpenRead(filePath); openedFiles.Add(new OpenedFile(stream, fileName)); } } return new OpenFileResult(openedFiles); }
private void BtnImportClick(object sender, RoutedEventArgs e) { var ofd = new OpenFileDialog { Filter = "Text files (*.txt)|*.txt" }; var result = ofd.ShowDialog(); if (result == true) { if (!File.Exists(ofd.FileName)) { return; } var accounts = Utils.GetLogins(ofd.FileName); var num = 0; foreach (var account in accounts) { if (!Checker.Accounts.Exists(a => a.Username == account.Username)) { Checker.Accounts.Add(account); num++; } } this.ShowMessageAsync( "Import", num > 0 ? string.Format("Imported {0} accounts.", num) : "No new accounts found."); RefreshAccounts(); MainWindow.Instance.UpdateControls(); } }
public void Run() { OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog.Filter = "Zip Files (*.zip)|*.zip|" + Utility.AllFilesFilter; if (openFileDialog.ShowDialog() == true) { WaitWindow waitWindow = new WaitWindow("Importing collection..."); waitWindow.ShowDialog(this.ParentWindow, () => { try { using (CollectionImporterBase importer = new ArchivedCollectionImporter(openFileDialog.FileName, this.CollectionManager)) { importer.Import(); } } catch (Exception ex) { Utility.WriteToErrorLog("Error importing: " + ex.ToString()); MessageBox.Show("Error importing backup: " + ex.Message); } this.ParentWindow.Dispatcher.BeginInvokeAction(() => { CollectionManagerGlobal.OnCollectionChanged(); }); }); } }
/// <summary> /// Получеение открытого файла. /// </summary> /// <returns>Коллекцию</returns> public static ProjectVm OpenFile() { var dialog = new OpenFileDialog { FileName = "ListOfTasks", DefaultExt = ".xml", Filter = "(*.xml, *.csv)|*.xml;*.csv" }; var result = dialog.ShowDialog(); if (result != true) return null; var tasks = ReadTasksFromFile(dialog.FileName); if (tasks == null) { return null; } var projectVm = new ProjectVm { ListOfTasks = tasks }; ConfigHelper.UpdateLastProject(new Project(dialog.FileName)); return projectVm; }
private void SetLoggerPath_Click(object sender, RoutedEventArgs e) { // Configure open file dialog box Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog(); dlg.FileName = "Document"; // Default file name dlg.DefaultExt = ".txt"; // Default file extension dlg.InitialDirectory = @"C:\Users\Public"; dlg.Filter = "Text documents (.txt)|*.txt"; // Filter files by extension // Show open file dialog box Nullable <bool> result = dlg.ShowDialog(); // Process open file dialog box results if (result == true) { // Open document string filename = dlg.FileName; SetLoggerFilename(filename); } }
/// <summary> /// Открывает диалоговое окно для чтения из файла токена /// </summary> public static string OpenFileDialogToken() { OpenFileDialog openFileDialog = new Microsoft.Win32.OpenFileDialog(); openFileDialog.Title = "Открыть файл"; openFileDialog.Filter = "files (*.txt)|*.txt"; openFileDialog.InitialDirectory = AppDomain.CurrentDomain.BaseDirectory; if (openFileDialog.ShowDialog() == true) { PathFile = openFileDialog.FileName; if (Path.GetExtension(PathFile) == ".txt") { return(FileIOService.OpenAsTXT(PathFile)); } } return(null); }
//按钮[读取场景] 被点击的事件处理器 private void BtnLoad_Click(object sender, RoutedEventArgs e) { openFileDialog.Filter = dialogFilter[ITrainerExtension.Lang.Id]; openFileDialog.Title = loadText[ITrainerExtension.Lang.Id]; if (openFileDialog.ShowDialog() == true)//如果打开文件对话框选到了文件 { //先清空LawnScene中的对象 LawnScene.Children.Clear(); using (FileStream file = File.OpenRead(openFileDialog.FileName)) //创建文件流进行读取 { byte[] buffer = new byte[4]; //缓冲区定义 file.Read(buffer, 0, buffer.Length); //读取文件头数据 if (Encoding.Default.GetString(buffer) == ".izf") //如果文件头符合 { int count = file.ReadByte(); //读取对象数量 for (int i = 0; i < count; i++) { //并将所表示的Image创建,加入到LawnScene中 Image image = new Image(); image.IsHitTestVisible = false; int row = file.ReadByte(); int column = file.ReadByte(); int type = file.ReadByte(); image.Source = PlantImages[type]; Grid.SetRow(image, row); Grid.SetColumn(image, column); if (type == (int)PVZ.PlantType.CobCannon) { Grid.SetColumnSpan(image, 2); } if (type == (int)PVZ.PlantType.Tallnut) { Grid.SetRowSpan(image, 2); } image.Tag = type; LawnScene.Children.Add(image); } } } } }
private void LoadXMLClick() { MessageProcessor processor = new MessageProcessor(); // Create OpenFileDialog Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog(); // Set filter for file extension and default file extension dlg.DefaultExt = ".xml"; // Display OpenFileDialog by calling ShowDialog method Nullable <bool> result = dlg.ShowDialog(); // Get the selected file name if (result == false) { return; } this.pathToXML = dlg.FileName; MessageBox.Show(pathToXML); XmlDocument doc = new XmlDocument(); doc.Load(@pathToXML); XmlNodeList XmlDocNodes = doc.SelectNodes("/Messages/Message"); foreach (XmlNode node in XmlDocNodes) { Message mes = new Message(node["Header"].InnerText, node["Sender"].InnerText, node["Subject"].InnerText, p.replaceAbreviations(node["Body"].InnerText) ); mes.Type = processor.SetType(mes.Header); this.MessageList.Add(mes); if (p.validateSirFromFile(mes.Subject)) { this.SirList.Add(mes); } } }
//选择图片 private void choose_Click(object sender, RoutedEventArgs e) { fixPoint.Clear(); targetPoint.Clear(); excute.IsEnabled = true; clear.IsEnabled = true; reset.IsEnabled = false; OpenFileDialog op = new Microsoft.Win32.OpenFileDialog(); op.InitialDirectory = @"c:\"; op.RestoreDirectory = true; op.Filter = "图片文件|*.jpg;*.bmp;*.png"; op.ShowDialog(); dir.Text = op.FileName; if (op.FileName == "") { return; } imagesource = op.FileName; img.Source = new BitmapImage(new Uri(op.FileName, UriKind.Absolute)); Bitmap bmp = new Bitmap(op.FileName); System.Drawing.Color pixelColor; r = bmp.Height + 4; c = bmp.Width + 4; map = new int[2, c, r, 3]; img.Height = bmp.Height; img.Width = bmp.Width; for (int i = 0; i < c - 4; ++i) { for (int j = 0; j < r - 4; ++j) { pixelColor = bmp.GetPixel(i, j); map[0, i + 2, j + 2, 0] = pixelColor.R; map[0, i + 2, j + 2, 1] = pixelColor.G; map[0, i + 2, j + 2, 2] = pixelColor.B; } } dir.Width = (img.Width - 90) > 0 ? (img.Width - 90) : 0; }
public void Execute(object parameter) { OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog(); dlg.FileName = "Document"; // přednastavené jméno souboru dlg.DefaultExt = ".xml"; // přednastavená přípona souboru dlg.Filter = "Xml documents (.xml)|*.xml"; // filter soubotů podle přípony // ukaž dialogové okno pro otevření souboru Nullable <bool> result = dlg.ShowDialog(); // výsledek dialogového okna pro otevření souborů if (result == true) { // otevření dokumentu string filename = dlg.FileName; // Vyjímka pro úspěšné načtení správného dokumentu try { XDocument.Load(filename); } catch (Exception ex) { MessageBox.Show(ex.Message, "Chyba - načtěte prosím .xml soubor.", MessageBoxButton.OK, MessageBoxImage.Exclamation); return; } auta = XDocument.Load(filename); } if (auta != null) { BaseListMaker baseListMaker = new BaseListMaker(); if (baseListMaker.GetList(auta)) { this.Model.AutaZakladni = baseListMaker.AutaZakladni; } OnTableLoaded(); } }
private void LoadGroupBtn_Click(object sender, RoutedEventArgs e) { Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog(); // Set filter for file extension and default file extension dlg.DefaultExt = ".txt"; //dlg.Filter = "JPEG Files (*.jpeg)|*.jpeg|PNG Files (*.png)|*.png|JPG Files (*.jpg)|*.jpg|GIF Files (*.gif)|*.gif"; dlg.Filter = "INI Files (*.ini)|*.ini"; string ch = string.Format("ch{0:d2}", m_nCh); string initPath = AppDomain.CurrentDomain.BaseDirectory + ch; dlg.InitialDirectory = initPath; // Display OpenFileDialog by calling ShowDialog method Nullable <bool> result = dlg.ShowDialog(); // Get the selected file name and display in a TextBox if (result == true) { string selectedFilePathName = dlg.FileName; //불러온경로를 저장 m_presetChInfoIni.presetPathName = selectedFilePathName; m_presetChInfoIni.WriteIni(m_nCh); //파일 이름만 추출 int index1 = dlg.FileName.LastIndexOf('\\'); int index2 = dlg.FileName.LastIndexOf('.'); FileNameLabel.Content = dlg.FileName.Substring(index1 + 1, (index2 - 1) - index1); int nIndex = m_nCh - 1; //파일 불러오기 m_arrPresetListReadWrite[nIndex].LoadFIle(dlg.FileName); //리스트를 초기화 한다. PresetListView.ItemsSource = m_arrPresetListReadWrite[nIndex].GetPresetList(); } }
private void btnProtocolFromFile_Click(object sender, RoutedEventArgs e) { bool status = false; Microsoft.Win32.OpenFileDialog openFileDialog = new Microsoft.Win32.OpenFileDialog(); openFileDialog.Filter = "Text files (*.txt)|*.txt"; //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // czy jest jakas zmienna srodowiskowa mowiaca o folderze w którym znajduje sie projekt?? openFileDialog.InitialDirectory = @"c:\repozytoria\PopulationProtocolMgr\protocols"; if (openFileDialog.ShowDialog() == true) { pathToProtocolFile = openFileDialog.FileName; //load info about protocol to richBox and activate field's to add a graph status = validateFile(pathToProtocolFile, "protocol"); if (status) { status = createFileWithProtocolInfo(pathToProtocolFile); } else { pathToProtocolFile = ""; txtPathProtocol.Text = pathToProtocolFile; txtInfoProtocol.Document.Blocks.Clear(); txtInfoProtocol.AppendText("No protocol uploaded."); //System.Windows.MessageBox.Show("This file doesn't contains protocol! Select other file."); groupBxGraphSettings.IsEnabled = false; } if (status) { clearGraphAndSimulationField(); txtPathProtocol.Text = pathToProtocolFile; loadInfoProtocolFromFile(); inputAlphabetTemp = createDictionaryWithInputAlphabet(pathToProtocolFile); groupBxGraphSettings.IsEnabled = true; btnLoadNewGraph.IsEnabled = false; } } }
private void OpenFile_Click(object sender, RoutedEventArgs e) { Microsoft.Win32.OpenFileDialog opf = new Microsoft.Win32.OpenFileDialog(); //opf.Filter = "Wavefront file (.obj)|*.obj"; // removed .mesh and .xml import for public release opf.Filter = "Stormworks mesh files (.mesh)|*.MESH|XML file (.xml)|*.xml|Wavefront file (.obj)|*.obj|Stormworks physics files (.phys)|*.PHYS"; outTextBox.Width = double.NaN; outTextBox.TextWrapping = TextWrapping.NoWrap; Nullable <bool> r = opf.ShowDialog(); if (r == true) { saveFile.IsEnabled = false; if (System.IO.Path.GetExtension(opf.FileName) == ".mesh") { this.fileType = "mesh"; outTextBox.Clear(); openMesh(opf.FileName); genPhys.IsEnabled = false; } else if (System.IO.Path.GetExtension(opf.FileName) == ".obj") { this.fileType = "obj"; outTextBox.Clear(); openObj(opf.FileName); toXML.IsEnabled = false; } else if (System.IO.Path.GetExtension(opf.FileName) == ".phys") { outTextBox.Text = swMesh2XML.Phys.ToXml(File.ReadAllBytes(opf.FileName)); } { showError("This isnt implemented yet, sorry"); //this.fileType = "xml"; //openXml(opf.FileName); } } }
//open picture private void Button_Click_7(object sender, RoutedEventArgs e) { OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog(); dlg.ShowDialog(); try { FileStream fs = new FileStream(dlg.FileName, FileMode.Open, FileAccess.Read); byte[] data = new byte[fs.Length]; fs.Read(data, 0, System.Convert.ToInt32(fs.Length)); fs.Close(); con.Open(); SqlCommand sc = new SqlCommand("insert into mugshots(data, name, prisoner_id) values(@d, @n, @i)", con); sc.Parameters.AddWithValue("@d", data); sc.Parameters.AddWithValue("@n", mp_name.Text); sc.Parameters.AddWithValue("@i", mp_id.Text); sc.ExecuteNonQuery(); con.Close(); ImageSourceConverter imgs = new ImageSourceConverter(); picturebox.SetValue(Image.SourceProperty, imgs. ConvertFromString(dlg.FileName.ToString())); MessageBox.Show("New Mugshot Pictures is Saved!"); //audittrail // dashboard d = new dashboard(); // audittrail au = new audittrail(); // au.users = d.username.Text.ToString(); // au.activity = "added a mugshot to a prisoner"; // au.dateOfActivity = DateTime.Now.ToString(); // au.timeOfActivity = DateTime.Now.ToString("G"); // au.add(); } catch { } }
// ------------------------------ OnOpen ------------------------------ /// <summary> /// Handles the user "File | Open" menu operation.</summary> private void OnOpen(object target, ExecutedRoutedEventArgs args) { // Create a "File Open" dialog positioned to the // "Content\" folder containing the sample images. WinForms.OpenFileDialog dialog = new WinForms.OpenFileDialog(); dialog.InitialDirectory = GetContentFolder(); dialog.CheckFileExists = true; dialog.Filter = "Image files (*.png,*.jpg,*.jpeg, *.protected)|" + "*.png;*.jpg;*.jpeg;*.protected|All (*.*)|*.*"; // Show the "File Open" dialog. If the user // clicks "Cancel", cancel the File|Open operation. if (dialog.ShowDialog() != true) return; // clicks "OK", load and display the specified file. CloseContent(); // Close current file if open. _contentFile = dialog.FileName; // Save new path and file name. ShowStatus("Opening '" + Filename(_contentFile) + "'"); // Check to see if the file name shows as "protected" or // "encrypted". If encrypted, use OpenEncryptedContent(). bool opened; if ( _contentFile.ToLower().Contains("protected") || _contentFile.ToLower().Contains("encrypted") ) opened = OpenEncryptedContent(_contentFile); // Otherwise open as unencrypted. else opened = OpenContent(_contentFile); // If the file was successfully opened, show the file name, // enable File|Close, and give focus to the Image control. if (opened == true) { this.Title = "RightsManagedContentViewer SDK Sample - " + Filename(_contentFile); menuFileClose.IsEnabled = true; imageViewer.Focus(); } }// end:OnOpen()
private void Button_Click_Load(object sender, RoutedEventArgs e) { var dialogue = new Microsoft.Win32.OpenFileDialog() { Filter = "Database file (*.mbf)|*.mdf" }; var result = dialogue.ShowDialog(); if (result == false) { return; } string path = dialogue.FileName; DataBaseMainModel temp = new DataBaseMainModel(); temp.path = path; fbpresenter = new FileBasePresenter(this, temp); CallEventDB(((Button)sender).Content.ToString()); databaseJson.Items.Refresh(); databaseBin.Items.Refresh(); }
//*************************************Reutilisation****************************************** #region Réeutilisation private void TextBlock_MouseRightButtonDown(object sender, MouseButtonEventArgs e) { Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog(); dlg.DefaultExt = ".xaml"; // Default file extension dlg.Filter = "Xaml File (.xaml)|*.xaml"; // Filter files by extension // Show open file dialog box Nullable <bool> result = dlg.ShowDialog(); // Process open file dialog box results if (result == true) { string filename = dlg.FileName; String nom = dlg.SafeFileName.Replace(".xaml", " "); CircuitPersonnalise personnalise = Reutilisation(filename); personnalise.setLabel(nom); CircuitComplet gate = new CircuitComplet(personnalise); this.circuit.AddComponent(personnalise); gate.added = true; Grille.Children.Add(gate); } }
//檔案->開啟舊檔 功能 private void Loading_Click(object sender, RoutedEventArgs e) { Doing.Content = "開啟舊檔...."; Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); OpenFileDialog openfile = new OpenFileDialog(); openfile.DefaultExt = ".txt"; openfile.Filter = "文字文件|*.txt|全部文件|*.*"; if (openfile.ShowDialog() == true) { string path = openfile.FileName; var reader = new StreamReader(path, Encoding.GetEncoding("big5"));//var不明確的宣告 Text_in.Text = File.ReadAllText(path); Save_path = path; is_Save = true; window.Title = openfile.SafeFileName + " - 記事本"; } Doing.Content = "就緒...."; }
private void OpenFile_Click(object sender, RoutedEventArgs e) { Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog(); dlg.Filter = "top files (*.top)|*.top"; dlg.Title = "Please select an top file to open."; Nullable <bool> result = dlg.ShowDialog(); if (result == true) { string filename = dlg.FileName; using (BinaryReader b = new BinaryReader(File.Open(filename, FileMode.Open))) { int pos = 0; int length = (int)b.BaseStream.Length; this.topFile = new TopFile(b); LoadGrid(); } } }
/** * Permite abrir un nuevo texto */ private void Open_Click(object sender, EventArgs e) { OpenFiles = new Microsoft.Win32.OpenFileDialog(); //Preparo el openFile con las opciones necesarias OpenFiles.InitialDirectory = "c:\\"; //Primer directorio OpenFiles.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*|rtf files (*.rtf)|*.rtf"; //Filtra ficheros de texto y rtf OpenFiles.FilterIndex = 2; OpenFiles.RestoreDirectory = true; if (OpenFiles.ShowDialog() == true) { //Get the path of specified file filePath = OpenFiles.FileName; rutas.Items.Add(filePath); selectedPath = filePath.ToString(); System.Windows.MessageBox.Show("Fichero cargado con exito"); leeArchivo(); } }
private string fileSelect_dialog() { // Create OpenFileDialog Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog(); // Set filter for file extension and default file extension dlg.DefaultExt = ".vhdx"; dlg.Filter = "VHDX Files (*.vhdx)|*.vhdx|All Files (*.*)|*.*"; // Display OpenFileDialog by calling ShowDialog method Nullable <bool> result = dlg.ShowDialog(); // Get the selected file name and return the value if (result == true) { // Open document string filename = dlg.FileName; return(filename); } return("No file selected"); }
private void checkBox3_Checked(object sender, RoutedEventArgs e) { checkBox4.IsChecked = false; textBox3.IsEnabled = true; textBox4.Clear(); textBox3.Clear(); Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog(); dlg.FileName = "Document"; // Default file name dlg.DefaultExt = ".txt"; // Default file extension dlg.Filter = "Text documents (.txt)|*.txt"; // Filter files by extension // Show open file dialog box Nullable <bool> result = dlg.ShowDialog(); // Process open file dialog box results if (result == true) { // Open document string path = dlg.FileName; textBox3.Text = odczyt_z_pliku(path); } }
private void FindStartupKeyboardFile(object sender, System.Windows.RoutedEventArgs e) { Microsoft.Win32.OpenFileDialog openFileDialog = new Microsoft.Win32.OpenFileDialog { Filter = "XML keyboard definition (*.xml)|*.xml" }; if (File.Exists(txtStartupKeyboardLocation.Text)) { openFileDialog.InitialDirectory = Path.GetDirectoryName(txtStartupKeyboardLocation.Text); } if (openFileDialog.ShowDialog() == true) { if (openFileDialog.FileName.EndsWith(@".xml")) { // This is hooked up to the DynamicKeyboardsLocation property txtStartupKeyboardLocation.Text = openFileDialog.FileName; } } }
private void Grava_Imagem() { Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog(); dlg.ShowDialog(); try { System.IO.FileStream fs = new System.IO.FileStream(dlg.FileName, FileMode.Open, FileAccess.Read); byte[] dadosImagem = new byte[fs.Length]; fs.Read(dadosImagem, 0, System.Convert.ToInt32(fs.Length)); fs.Close(); ImageSourceConverter imgs = new ImageSourceConverter(); PicFoto.SetValue(Image.SourceProperty, imgs.ConvertFromString(dlg.FileName.ToString())); Textnome.Text = dlg.FileName.ToString(); } catch (Exception ex) { MessageBox.Show("Erro :: " + ex.Message); } }
private void ButtonOnClick(object sender, RoutedEventArgs routedEventArgs) { var dlg = new Microsoft.Win32.OpenFileDialog() // Set filter for file extension and default file extension { Filter = "OBJ files (*.obj)|*.obj|STL files (*.stl)|*.stl|All files (*.*)|*.*", InitialDirectory = @"C:\", Title = "Please select a file." }; // Display OpenFileDialog by calling ShowDialog method var result = dlg.ShowDialog(); // Get the selected file name and display in a TextBox if (result != true) { return; } // Set TextBox textBox.Text = dlg.FileName; }
private void Browserbtn_Click(object sender, RoutedEventArgs e) { var screen = new Microsoft.Win32.OpenFileDialog(); screen.Multiselect = true; screen.Filter = "Music files (.mp3)|*.mp3; *.MP3"; if (screen.ShowDialog() == true) { foreach (var item in screen.FileNames) { SongDirectory.Add(item); var info = new FileInfo(item); _fullPaths.Add(info); } if (random == true) { randomList = createRandomList(); } } }
// Load File Dialog private void mnu_LOAD(object sender, RoutedEventArgs e) { //configure save file dialog box Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog(); dlg.FileName = "config"; //default file name dlg.DefaultExt = ".xml"; //default file extension dlg.Filter = "XML documents (.xml)|*.xml"; //filter files by extension // Show save file dialog box Nullable <bool> result = dlg.ShowDialog(); // Process save file dialog box results if (result == true) { Stream load_stream = dlg.OpenFile(); RSS_LogicEngine.Component_View component_view; component_view = RSS_LogicEngine.Component_View.Get_Instance(); component_view.Load_Components(load_stream); load_stream.Close(); } }
private string OpenFileDialog() { Microsoft.Win32.OpenFileDialog dialog = new Microsoft.Win32.OpenFileDialog(); //dialog.InitialDirectory = @"C:"; dialog.InitialDirectory = @"E:\Download\rvl-cdip"; dialog.DefaultExt = ".txt"; dialog.Filter = ".TXT Files (*.txt)|*.txt"; Nullable <bool> result = dialog.ShowDialog(); if (result == true) { return(dialog.FileName); } else { SetStatusImage(imgPathLabels, "img/alert.png"); return("Error browsing for file!"); } }
private void ButtonChooseFile_Click(object sender, RoutedEventArgs e) { // Create OpenFileDialog Microsoft.Win32.OpenFileDialog openFileDlg = new Microsoft.Win32.OpenFileDialog(); string fileName; // Launch OpenFileDialog by calling ShowDialog method Nullable <bool> result = openFileDlg.ShowDialog(); // Get the selected file name and display in a TextBox. // Load content of file in a TextBlock if (result == true) { fileName = openFileDlg.FileName; if (bt.choosenDevice != null) { bt.SendTempFile(fileName); } } }
public void OpenFile() { // ofd to open a file. Regex checks if file is a png or text file and treats it accordingly. OpenFileDialog ofd = new Microsoft.Win32.OpenFileDialog(); ofd.Filter = "Text Files (*.txt)|*.txt|PNG(*.png)|*.png|All Files (*.*)|*.*"; if (ofd.ShowDialog() == true) { filePath = ofd.FileName; Regex regex = new Regex(@"\.png\s$", RegexOptions.IgnoreCase); Match match = regex.Match(filePath); if (match.Success) { OpenPNGImage(); } else { textBox1.Text = File.ReadAllText(filePath); } } }
private void AddNewFileToModelList() { OpenFileDialog fileDialog = new OpenFileDialog(); fileDialog.Filter = "Obj files (*.obj)|*.obj"; Nullable <bool> result = fileDialog.ShowDialog(); string newModel; if (result == true) { newModel = fileDialog.FileName; string directoryPath = System.IO.Path.GetDirectoryName(fileDialog.FileName); string newModelName = Path.GetFileNameWithoutExtension(newModel); File.Copy(newModel, $"C:/Users/Anastasiia/source/repos/My_3d_WFP_App/furniture/{Path.GetFileName(newModel)}"); modelList.Add($"C:/Users/Anastasiia/source/repos/My_3d_WFP_App/furniture/{Path.GetFileName(newModel)}"); myScene.AddElement(newModel); lvScene.ItemsSource = myScene.Names; } lvScene.Items.Refresh(); }
/// <summary> /// 从清单比较 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Btn_CompareFromList_Click(object sender, RoutedEventArgs e) { try { var ofd = new OpenFileDialog(); ofd.Title = "请选择一个清单文件..."; ofd.Filter = "清单文件|*.txt"; ofd.ShowDialog(); if (ofd.FileName == null || ofd.FileName == "" || Tbx_FolderPath.Text == "") { return; } var currTime = DateTime.Now; var arr = File.ReadAllLines(ofd.FileName); var dict2 = new Dictionary <string, string>(); foreach (var line in arr) { var _arr = line.Split(','); dict2.Add(_arr[0], _arr[1]); } FileList.Clear(); GetFolderFileList(Tbx_FolderPath.Text); var dict1 = CalcFileList(Tbx_FolderPath.Text); var dt = CompareTwoSource(dict1, dict2, Tbx_FolderPath.Text, $@"清单文件:{ofd.FileName}"); var endTime = DateTime.Now; dataGrid_Main.ItemsSource = dt.DefaultView; MessageBox.Show($@"目录比对完成,共计比对{dict1.Count + dict2.Count}个文件,耗时{Math.Round((endTime - currTime).TotalSeconds)}秒!"); } catch (Exception ex) { MessageBox.Show($@"从清单比较异常,{ex.Message}"); } }
private void SendFileButton_Click(object sender, RoutedEventArgs e) { OpenFileDialog ofd = new Microsoft.Win32.OpenFileDialog(); ofd.Filter = "All Files (*.*)|*.*"; ofd.Multiselect = false; if (ofd.ShowDialog() == true) { FileInfo file = new FileInfo(ofd.FileName); if (file.Length > 2000000) { MessageBox.Show("文件太大,无法传输!"); return; } if (file.Length <= 0) { MessageBox.Show("请不要传输空文件!"); return; } String url = (String)ofd.FileName; object[] obj = (object[])mw.getFriendItemById[this.key].DataContext; if (((String)obj[4]).Equals(" 在线")) //在线 { if (MessageBox.Show("是否使用离线传送功能?", "消息", MessageBoxButton.YesNo, MessageBoxImage.Question).Equals(MessageBoxResult.Yes)) //离线发送 { //离线发送 mw.SendMessage("offlnfile", new String[] { this.key, url }); } else//在线传送 { mw.SendMessage("onlnfile", new String[] { this.key, url }); } } else//离线 { //离线传送 mw.SendMessage("offlnfile", new String[] { this.key, url }); } } }
static public void GeneratorTemplatesCreate(string databaseFile) { ofd.Filter = "Xml-Template Configuration|*.xml|All files|*"; #if WPF4 if (!ofd.ShowDialog().Value) { return; } #else if (ofd.ShowDialog() != DialogResult.OK) { return; } #endif GeneratorTemplatesCreate(databaseFile, ofd.FileName); }