/// <summary> /// Creates a new instance of the <see cref="ColorCollection" /> class that contains elements loaded from the specified file. /// </summary> /// <param name="fileName">Name of the file to load.</param> /// <exception cref="System.ArgumentNullException">Thrown if the <c>fileName</c> argument is not specified.</exception> /// <exception cref="System.IO.FileNotFoundException">Thrown if the file specified by <c>fileName</c> cannot be found.</exception> /// <exception cref="System.ArgumentException">Thrown if no <see cref="IPaletteSerializer"/> is available for the file specified by <c>fileName</c>.</exception> public static ColorCollection LoadPalette(string fileName) { IPaletteSerializer serializer; if (string.IsNullOrEmpty(fileName)) { throw new ArgumentNullException(nameof(fileName)); } if (!File.Exists(fileName)) { throw new FileNotFoundException(string.Format("Cannot find file '{0}'", fileName), fileName); } serializer = PaletteSerializer.GetSerializer(fileName); if (serializer == null) { throw new ArgumentException(string.Format("Cannot find a palette serializer for '{0}'", fileName), nameof(fileName)); } using (FileStream file = File.OpenRead(fileName)) { return(serializer.Deserialize(file)); } }
private void loadPaletteButton_Click(object sender, EventArgs e) { using (FileDialog dialog = new OpenFileDialog { Filter = PaletteSerializer.DefaultOpenFilter, DefaultExt = "pal", Title = "Open Palette File" }) { if (dialog.ShowDialog(this) == DialogResult.OK) { try { IPaletteSerializer serializer; serializer = PaletteSerializer.GetSerializer(dialog.FileName); if (serializer != null) { ColorCollection palette; if (!serializer.CanRead) { throw new InvalidOperationException("Serializer does not support reading palettes."); } using (FileStream file = File.OpenRead(dialog.FileName)) { palette = serializer.Deserialize(file); } if (palette != null) { // we can only display 96 colors in the color grid due to it's size, so if there's more, bin them while (palette.Count > 96) { palette.RemoveAt(palette.Count - 1); } // or if we have less, fill in the blanks while (palette.Count < 96) { palette.Add(Color.White); } colorGrid.Colors = palette; } } else { MessageBox.Show("Sorry, unable to open palette, the file format is not supported or is not recognized.", "Load Palette", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } catch (Exception ex) { MessageBox.Show(string.Format("Sorry, unable to open palette. {0}", ex.GetBaseException().Message), "Load Palette", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } }