Test Foro de elhacker.net SMF 2.1

Programación => Programación General => .NET (C#, VB.NET, ASP) => Mensaje iniciado por: Meta en 10 Junio 2015, 04:59 AM

Título: Leer una clase en un formulario Windows de Visual C#
Publicado por: Meta en 10 Junio 2015, 04:59 AM
Buenas:

Voy a empezar desde el principio. El código lo he sacado de esta Web.

https://github.com/Zeokat/SNES-ROM-Header-Dumper-CSharp/blob/master/snes_dumper.cs

El archivo se llama snes_dumper.cs.

Creo un proyecto nuevo. Se que lo expliqué pero haré lo mismo por si acaso no me haya expresado bien o no he entendido bien. Uso Visual C# Express 2013. Hay gente que me recomienda el VS Comunity, ni sabía su existencia, no se de que va ni ventajas que tiene y no se si es gratuito como el Express, esto es otra historia.

Archivo-->Nuevo Proyecto...
(http://www.subeimagenes.com/img/re2-1345995.png)

A crear una clase nueva en, PROYECTO-->Agregar clase...
(http://www.subeimagenes.com/img/re2-1345997.png)

Le pongo el nombre de la clase llamado snes_dumper.cs, como indica abajo, luego pulso el botón Agregar.
(http://www.subeimagenes.com/img/re2-1346000.png)

Seañade la calse snes_dumper.cs como muestra abajo. El código generado a borrarlo.
(http://www.subeimagenes.com/img/re2-1346001.png)

He copiado el código que descargué en la Web de origen dentro del archivo snes_dumper.cs en el formulario como puedes ver abajo.
(http://www.subeimagenes.com/img/re2-1346005.png)

¿Qué es lo que quiero?

1) Con un botón leer el archivo *.smc, es una ROM, un archivo binario.
2) Lo que lea la clase snes_dumper.cs lo tiene que mostrar en sus textBox correspondiente en el Form1.

La mayoría de los datos que quiero visualizar en el TextBox son estas variables.
Código (csharp) [Seleccionar]
      // Los diferentes datos que obtenemos de la ROM
       public string Name;
       public byte Layout;
       public byte CartridgeType;
       public byte RomSize;
       public byte RamSize;
       public byte CountryCode;
       public byte LicenseCode;
       public byte VersionNumber;
       ushort Checksum;
       ushort ChecksumCompliment;
       public BankTypeEnum BankType;


Hay 11 variables en el primer Cuadro en verde. Esas 11 variables es lo que tengo que leer en el textBox. La lectura lo hace a la hora de pulsar un botón, seleccionar el archivo binario a leer y lo leído, lo muestra en el formulario. Les dejo el formulario hecho estilo colores y nombrado por Cuadros 1 al 4. El que me interesa mucho es el Cuadro 1 y el Cuadro 4 para cargar el archivo binario.
(http://www.subeimagenes.com/img/re2-1346029.png)

Los nombres de cada textBox están identificado por el nombre de sus variables así no te perderás. Digamos que esto es una plantilla con la clase snes_dumper.cs sin hacer nada, solo a la espera de ser programado.

Les dejo aquí para descargar esta plantilla por llamarlo de alguna manera, bueno, lo llamaremos proyecto vacío.

Descarga (https://www.dropbox.com/s/m2dzec96b69a4hq/ROM_SNES_alfa_v0.2.zip?dl=0)

Espero ayuda para leer esta clase. En resumen, quiero leer las variables que indiqué arriba y lo muestre en el Formulario que he hecho arriba de colorines.

Saludos.
Título: Re: Leer una clase en un formulario Widnows de Visual C#
Publicado por: Eleкtro en 10 Junio 2015, 07:39 AM
¿Y cual es el problema?, si ya tienes una Class que lo hace todo.

¿Y si en lugar de perdir que te lo hagan, mejor preguntas por lo que no entiendas de esa Class, para poder hacerlo por tus propios medios?.

Solo debes leer el archivo.smc de principio a fin para generar un array de Bytes, y pasarle esos bytes cómo argumento al constructor de la Class RomDump, el cual automaticamente llama al método ReadHeader y se asignan los valores a las propiedades de esa Class.

Es muy sencillo de realizar (en apenas 2 lineas de código), pero si no has entendido algo, especifica el que.

Te sugiero leer la documentación de los métodos de lectura de la Class System.IO.File, y la documentación de la Class System.IO.FileStream.

PD: Deja los copy/paste, ¡intenta aprender!.

Saludos!
Título: Re: Leer una clase en un formulario Widnows de Visual C#
Publicado por: Meta en 10 Junio 2015, 08:22 AM
Buenas campeón:

Buscando el IO.Stream (https://msdn.microsoft.com/es-es/library/system.io.filestream%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396) encontré códigos de ejemplo como este.

Me interesa leer, no modificar, al menos por ahora. Supuestamente es este por lo que veo.
Código (csharp) [Seleccionar]
       //Open the stream and read it back.
       using (FileStream fs = File.OpenRead(path))
       {
           byte[] b = new byte[1024];
           UTF8Encoding temp = new UTF8Encoding(true);
           while (fs.Read(b,0,b.Length) > 0)
           {
               Console.WriteLine(temp.GetString(b));
           }
       }


Viendo File.ReadAllBytes (https://msdn.microsoft.com/es-es/library/system.io.file.readallbytes%28v=vs.110%29.aspx). En el Form1 hice este código.
Código (csharp,27) [Seleccionar]
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using System.IO; // No olvidar.

namespace ROM_SNES
{
   public partial class Form1 : Form
   {
       public Form1()
       {
           InitializeComponent();
       }

       private void button1_Click(object sender, EventArgs e)
       {

           if (openFileDialog1.ShowDialog() == DialogResult.OK)
           {
               SnesKit.RomDump VARIABLE = new SnesKit.RomDump(File.ReadAllBytes(textBox_Nombre_de_archivo.Text.ToString()));
               textBox_Nombre_ruta_archivo.Text = openFileDialog1.FileName.ToString(); // Muestra la ruta del archivo.
           }
       }
   }
}


Lo ejecuta efectivamente, si pulso el botón abrir, muestra este error.
CitarExcepción no controlada del tipo 'System.ArgumentException' en mscorlib.dll

Información adicional: No se puede dejar vacío el nombre de la ruta de acceso.

Encontré lo que dice del System.ArgumentException (https://msdn.microsoft.com/es-es/library/system.argumentexception%28v=vs.110%29.aspx). Ahí no entiendo nada.

Estoy haciendo pruebas por si acaso. :)

Dejo lo que hice en este enlace.

Descarga (https://www.dropbox.com/s/nnqy544jtoh2ykb/ROM_SNES_Alfa_v0.3.zip?dl=0) Proyecto alfa v0.3. (incluye una rom de 4 MB).

Saludos.
Título: Re: Leer una clase en un formulario Widnows de Visual C#
Publicado por: Eleкtro en 10 Junio 2015, 09:27 AM
Con el mensaje de error puedes deducir que la propiedad 'Text' del control 'textBox_Nombre_de_archivo' está vacía, ya que le estás pasando un argumento vacío a la función 'Readallbytes', y esto significa que estás intentando utilizar dicha propiedad antes de haberle asignado ninguna ruta de archivo.

Utiliza la propiedad 'FileName' de la instancia de ese diálogo 'OpenFileDialog'.

Saludos!
Título: Re: Leer una clase en un formulario Widnows de Visual C#
Publicado por: Meta en 10 Junio 2015, 11:04 AM
Hola Señor:

Lo he hecho así, me ejecuta, no da problemas, no se si realmente así funciona. Ahora te toca hacer algo como esto a ver que tal.
Código (csharp) [Seleccionar]
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using System.IO; // No olvidar.

namespace ROM_SNES
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                SnesKit.RomDump VARIABLE = new SnesKit.RomDump(File.ReadAllBytes(openFileDialog1.FileName.ToString()));
                textBox_Nombre_ruta_archivo.Text = openFileDialog1.FileName.ToString(); // Muestra la ruta del archivo.
            }
        }
    }
}


Ahora estoy bien perdido para leer la variable Name del archivo Snes_dumper.cs.
Usando este otro código, no logro de ninguna manera leer algo de la ROM, al menos el nombre.
Código (csharp,25) [Seleccionar]
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using System.IO; // No olvidar.

namespace ROM_SNES
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            Mostar_Datos();
        }

            public void Mostar_Datos()
    {
         this.textBox_Name.Text  = RomDump.Name;
    }

        private void button1_Click(object sender, EventArgs e)
        {

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                SnesKit.RomDump VARIABLE = new SnesKit.RomDump(File.ReadAllBytes(openFileDialog1.FileName.ToString()));
                textBox_Nombre_ruta_archivo.Text = openFileDialog1.FileName.ToString(); // Muestra la ruta del archivo.
            }
        }
    }
}


Error   1   El nombre 'RomDump' no existe en el contexto actual   C:\Users\Usuario\Documents\Visual Studio 2013\Projects\ROM_SNES\ROM_SNES\Form1.cs   25   36   ROM_SNES

Da igual lo que haga, aquí si estoy perdido. Intento leer la classe pero no lo capto.

Saludos.
Título: Re: Leer una clase en un formulario Widnows de Visual C#
Publicado por: Eleкtro en 10 Junio 2015, 11:26 AM
Meta, fíjate bien en lo que estás haciendo ...leches xD.

La Class "RomDump" la estás declarando e instanciando en el bloque del event-handler "button1_Click", ahí es donde empieza y donde también termina la vida de ese objeto;
luego, tú estás haciendo un (mal) intento de leer esa instancia en otro método distinto, en el bloque del método "Mostar_Datos", no puedes leer una referencia que no existe.

1. Declara una variable 'snesRom' hacia una referencia vacía de la Class 'RomDump', fuera de cualquier método.
Código (csharp) [Seleccionar]
SnesKit.RomDump snesRom

2. Crea una instancia la Class 'RomDump' a la variable 'snesRom', dentro del handler "button1_Click" o dentro del método que prefieras.
Código (csharp) [Seleccionar]
this.snesRom = new SnesKit.RomDump(bytes);

3. Ya puedes leer la referencia de la propiedad 'snesRom.Name' donde quieras:
Código (csharp) [Seleccionar]
MessageBox.Show(snesRom.Name);

Saludos
Título: Re: Leer una clase en un formulario Widnows de Visual C#
Publicado por: Meta en 10 Junio 2015, 12:56 PM
Buenas honorable Elektro:

Para arriba y para abajo me salió esto.
Código (csharp) [Seleccionar]
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using System.IO; // No olvidar.

namespace ROM_SNES
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                SnesKit.RomDump VARIABLE = new SnesKit.RomDump(File.ReadAllBytes(openFileDialog1.FileName.ToString()));
                textBox_Nombre_ruta_archivo.Text = openFileDialog1.FileName.ToString(); // Muestra la ruta del archivo.

                textBox_RomSize.Text = VARIABLE.RomSize.ToString();
            }
        }
    }
}


(http://www.subeimagenes.com/img/autosave-1346254.gif)

Auí hay una Web perfecta para convertir códigos.
https://www.easycalculation.com/hex-converter.php

O verlo directamenta la tabla ASCII.
http://www.elcodigoascii.com.ar/codigo-americano-estandar-intercambio-informacion/codigo-ascii.gif

El 12 que presenta es decimal, quiero se se vea hexadecimal, que es 0C. (En C# se presenta así 0x0C).

Busqué aquí.
https://msdn.microsoft.com/es-es/library/bb311038.aspx?f=255&MSPPError=-2147217396

Este es el código que hice.
Código (csharp) [Seleccionar]
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using System.IO; // No olvidar.

namespace ROM_SNES
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                SnesKit.RomDump VARIABLE = new SnesKit.RomDump(File.ReadAllBytes(openFileDialog1.FileName.ToString()));
                textBox_Nombre_ruta_archivo.Text = openFileDialog1.FileName.ToString(); // Muestra la ruta del archivo.

                textBox_RomSize.Text = string.Format("{0:X}", VARIABLE.RomSize);
            }
        }
    }
}


Me sale la C. Quiero que salga 0C.
Título: Re: Leer una clase en un formulario Widnows de Visual C#
Publicado por: Eleкtro en 10 Junio 2015, 13:37 PM
Cita de: Meta en 10 Junio 2015, 12:56 PM
Auí hay una Web perfecta para convertir códigos.
https://www.easycalculation.com/hex-converter.php

O verlo directamenta la tabla ASCII.
http://www.elcodigoascii.com.ar/codigo-americano-estandar-intercambio-informacion/codigo-ascii.gif

El 12 que presenta es decimal, quiero se se vea hexadecimal, que es 0C. (En C# se presenta así 0x0C).

No necesitas recurrir a ningún servicio online ni tabla de caracteres, la librería de clases de .Net Framework tiene varias funciones built-in para llevar a cabo ese tipo de conversiones.

Convert.ToInt32 Method - MSDN (https://msdn.microsoft.com/en-us/library/sf1aw27b%28v=vs.110%29.aspx)
Convert.ToString Method - MSDN (https://msdn.microsoft.com/en-us/library/system.convert.tostring%28v=vs.110%29.aspx)
Convert.ToChar Method - MSDN (https://msdn.microsoft.com/en-us/library/system.convert.tochar%28v=vs.110%29.aspx)
y:
String.Format Method - MSDN (https://msdn.microsoft.com/en-us/library/system.string.format%28v=vs.110%29.aspx)

PD: Fíjate en el parámetro 'fromBase' de los overloads de la función Convert.ToInt32, y el parámetro 'toBase' de los overloads de la función Convert.ToString.

Ejemplo:
Código (vbnet) [Seleccionar]
String.Format("0x{0}", Convert.ToString(255, toBase:=16))

Saludos!
Título: Re: Leer una clase en un formulario Widnows de Visual C#
Publicado por: Meta en 10 Junio 2015, 13:44 PM
Entendido buen hombre:

Hice este código.
Código (csharp) [Seleccionar]
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using System.IO; // No olvidar.

namespace ROM_SNES
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                SnesKit.RomDump VARIABLE = new SnesKit.RomDump(File.ReadAllBytes(openFileDialog1.FileName.ToString()));
                textBox_Nombre_ruta_archivo.Text = openFileDialog1.FileName.ToString(); // Muestra la ruta del archivo.

                textBox_Name.Text = VARIABLE.Name;
                textBox_Layout.Text = string.Format("{0:X}", VARIABLE.Layout);
                textBox_CartridgeType.Text = string.Format("{0:X}", VARIABLE.CartridgeType);
                textBox_RomSize.Text = string.Format("{0:X}", VARIABLE.RomSize);
                textBox_RamSize.Text = string.Format("{0:X}", VARIABLE.RamSize);
                textBox_CountryCode.Text = string.Format("{0:X}", VARIABLE.CountryCode);
                textBox_LicenseCode.Text = string.Format("{0:X}", VARIABLE.LicenseCode);
                textBox_VersionNumber.Text = string.Format("{0:X}", VARIABLE.VersionNumber);
                textBox_BankType.Text = VARIABLE.BankType.ToString();
            }
        }
    }
}


Me salió este resultado. En los demás txtBox vacíos, no tengo la menor idea de como lograrlo, me machaqué las neuronas un poco por esta tontería.
(http://www.subeimagenes.com/img/autosave-1346289.gif)

El Cuadro 3 Azul si me sale, estaba haciendo pruebas, los demás no.

Saludo.
Título: Re: Leer una clase en un formulario Widnows de Visual C#
Publicado por: Eleкtro en 10 Junio 2015, 13:51 PM
El formato que le das al string es incorrecto, lee el ejemplo que he añadido en mi última respuesta.

Saludos!
Título: Re: Leer una clase en un formulario Widnows de Visual C#
Publicado por: Meta en 10 Junio 2015, 14:13 PM
Lo dejaré así mismo, me gusta.

Código (csharp) [Seleccionar]
textBox_Layout.Text = string.Format("0x{0}", VARIABLE.Layout);

Solo falta añadir los demás cuadros vacíos.
Título: Re: Leer una clase en un formulario Widnows de Visual C#
Publicado por: Eleкtro en 10 Junio 2015, 15:07 PM
Cita de: Meta en 10 Junio 2015, 14:13 PM
Lo dejaré así mismo, me gusta.

Código (csharp) [Seleccionar]
textBox_Layout.Text = string.Format("0x{0}", VARIABLE.Layout);

Pero eso que haces no tiene ningún sentido aunque te guste; "0x" es el prefijo estándar para un valor hexadecimal, pero la propiedad "Layout" devuelve un valor decimal entre 0 y 255, es decir, un Byte.

Si haces eso solo conseguirás mostrar resultados confusos en la UI.

Saludos!
Título: Re: Leer una clase en un formulario Windows de Visual C#
Publicado por: Meta en 10 Junio 2015, 19:32 PM
Haciendo pruebas o no me sale bien, algo se me escapa o C# no le gusta.

Código (csharp) [Seleccionar]
private void button1_Click(object sender, EventArgs e)
       {

           if (openFileDialog1.ShowDialog() == DialogResult.OK)
           {
               SnesKit.RomDump VARIABLE = new SnesKit.RomDump(File.ReadAllBytes(openFileDialog1.FileName.ToString()));
               textBox_Nombre_ruta_archivo.Text = openFileDialog1.FileName.ToString(); // Muestra la ruta del archivo.

               textBox_Name.Text = VARIABLE.Name;
               //textBox_Layout.Text = string.Format("0x{0}", VARIABLE.Layout);
               textBox_CartridgeType.Text = string.Format("0x{0}", VARIABLE.CartridgeType);
               textBox_RomSize.Text = string.Format("0x{0}", VARIABLE.RomSize);
               textBox_RamSize.Text = string.Format("0x{0}", VARIABLE.RamSize);
               textBox_CountryCode.Text = string.Format("0x{0}", VARIABLE.CountryCode);
               textBox_LicenseCode.Text = string.Format("0x{0}", VARIABLE.LicenseCode);
               textBox_VersionNumber.Text = string.Format("0x{0}", VARIABLE.VersionNumber);
               textBox_BankType.Text = VARIABLE.BankType.ToString();


                 textBox_Layout.Text = string.Format("0x{0}", Convert.ToString(255, toBase:=16));

           }
       }


Hay mucho errores.
Error   3   El término de la expresión ')' no es válido   C:\Users\Usuario\Documents\Visual Studio 2013\Projects\ROM_SNES\ROM_SNES\Form1.cs   41   96   ROM_SNES

Error   1   El término de la expresión '=' no es válido   C:\Users\Usuario\Documents\Visual Studio 2013\Projects\ROM_SNES\ROM_SNES\Form1.cs   41   93   ROM_SNES

Error   4   Se esperaba ;   C:\Users\Usuario\Documents\Visual Studio 2013\Projects\ROM_SNES\ROM_SNES\Form1.cs   41   96   ROM_SNES

Saludos.
Título: Re: Leer una clase en un formulario Windows de Visual C#
Publicado por: Eleкtro en 10 Junio 2015, 19:45 PM
Te voy a hacer un regalito :P ...es cosa tuya traducirlo a C#, o compilar el código en una dll para no tener que traducir.

La SNES siempre me ha fascinado, bueno, tengo cierta melancolía y bastantes roms por ahí perdidas xD, en fin, me ha interesado el tema, he cogido la Class que publicaste al principio del tema, y la he extendido para mejorarla en varios aspectos, añadiendo mayor y mejor documentación, así cómo nuevas funcionalidades.




Cosas a tener en cuenta:

1. Me ha sido imposible descifrar los 13 códigos de paises que se pueden usar en una ROM de SNES, no encuentro información sobre esto en ningún lugar, solo encontré información parcial en la que se dice que '0' equivale a Japón, '1' a U.S., y bajo mis propias conclusiones '8' debe ser España.
Si alguien conoce esta información al completo, que me lo haga saber, gracias.

2. No he testeado mi Class con cientos de ROMs para comprobar que todo funciona cómo debería funcionar a las mil maravillas en todas las circunstancias posibles, pero supongo que si, ya que me he basado en las especificaciones de la cabecera de SNES, las cuales ya estaban implementados en la Class original de donde saqué la idea.
Si alguien encuentra algún error, que me lo comunique, gracias.




A continuación publico el código fuente, y abajo del todo unos ejemplos de lectura y escritura:

Código (vbnet) [Seleccionar]
' ***********************************************************************
' Author   : Elektro.
'            Based on this 3rd party project:
'            https://github.com/Zeokat/SNES-ROM-Header-Dumper-CSharp/blob/master/snes_dumper.cs
' Modified : 10-June-2015
' ***********************************************************************
' <copyright file="SnesRom.vb" company="Elektro Studios">
'     Copyright (c) Elektro Studios. All rights reserved.
' </copyright>
' ***********************************************************************

#Region " Usage Examples "

' CONTENIDO OMITIDO...

#End Region

#Region " Option Statements "

Option Strict On
Option Explicit On
Option Infer Off

#End Region

#Region " Imports "

Imports System.IO
Imports System.Text

#End Region

Public NotInheritable Class SnesRom

#Region " Properties "

   ''' <summary>
   ''' Gets the raw byte-data of the ROM file.
   ''' </summary>
   ''' <value>The raw byte-data of the ROM file.</value>
   Public ReadOnly Property RawData As Byte()
       Get
           Return Me.rawDataB
       End Get
   End Property
   ''' <summary>
   ''' (backing field) The raw byte-data of the ROM file.
   ''' </summary>
   Private ReadOnly rawDataB As Byte()

   ''' <summary>
   ''' Gets The ROM header type.
   ''' </summary>
   ''' <remarks>http://romhack.wikia.com/wiki/SMC_header</remarks>
   ''' <value>The ROM header type.</value>
   Public ReadOnly Property HeaderType As HeaderTypeEnum
       Get
           Return Me.headerTypeB
       End Get
   End Property
   ''' <summary>
   ''' (backing field) The ROM header type.
   ''' </summary>
   Private headerTypeB As HeaderTypeEnum

   ''' <summary>
   ''' Gets the SNES header address location.
   ''' </summary>
   ''' <remarks>http://romhack.wikia.com/wiki/SNES_header</remarks>
   ''' <value>The SNES header address location.</value>
   Private ReadOnly Property HeaderLocation As Integer
       Get
           Return Me.headerLocationB
       End Get
   End Property
   ''' <summary>
   ''' (backing field) The SNES header address location.
   ''' </summary>
   Private headerLocationB As Integer = 33216

   ''' <summary>
   ''' Gets or sets the name of the ROM, typically in ASCII.
   ''' The name buffer consists in 21 characters.
   ''' </summary>
   ''' <remarks>http://romhack.wikia.com/wiki/SNES_header</remarks>
   ''' <value>The name of the ROM.</value>
   Public Property Name As String
       Get
           Return Me.nameB
       End Get
       Set(ByVal value As String)
           Me.SetName(value)
           Me.nameB = value
       End Set
   End Property
   ''' <summary>
   ''' (backing field) The name of the ROM.
   ''' </summary>
   Private nameB As String

   ''' <summary>
   ''' Gets the ROM layout.
   ''' The SNES ROM layout describes how the ROM banks appear in a ROM image and in the SNES address space.
   ''' </summary>
   ''' <remarks>http://romhack.wikia.com/wiki/SNES_ROM_layout</remarks>
   ''' <value>The ROM layout.</value>
   Public ReadOnly Property Layout As Byte
       Get
           Return Me.layoutB
       End Get
   End Property
   ''' <summary>
   ''' (backing field) The ROM layout.
   ''' </summary>
   Private layoutB As Byte

   ''' <summary>
   ''' Gets the bank type.
   ''' An image contains only LoROM banks or only HiROM banks, not both.
   ''' </summary>
   ''' <remarks>http://romhack.wikia.com/wiki/SNES_ROM_layout</remarks>
   ''' <value>The bank type.</value>
   Public ReadOnly Property BankType As BankTypeEnum
       Get
           Return Me.bankTypeB
       End Get
   End Property
   ''' <summary>
   ''' (backing field) The bank type.
   ''' </summary>
   Private bankTypeB As BankTypeEnum

   ''' <summary>
   ''' Gets the cartrifge type, it can be a ROM only, or a ROM with save-RAM.
   ''' </summary>
   ''' <remarks>http://romhack.wikia.com/wiki/SNES_header</remarks>
   ''' <value>The cartridge type.</value>
   Public ReadOnly Property CartridgeType As CartridgeTypeEnum
       Get
           Return Me.cartridgeTypeB
       End Get
   End Property
   ''' <summary>
   ''' (backing field) The cartrifge type.
   ''' </summary>
   Private cartridgeTypeB As CartridgeTypeEnum

   ''' <summary>
   ''' Gets the ROM size byte.
   ''' </summary>
   ''' <remarks>http://romhack.wikia.com/wiki/SNES_header</remarks>
   ''' <value>The ROM size byte.</value>
   Public ReadOnly Property RomSize As Byte
       Get
           Return Me.romSizeB
       End Get
   End Property
   ''' <summary>
   ''' (backing field) The ROM size byte.
   ''' </summary>
   Private romSizeB As Byte

   ''' <summary>
   ''' Gets the RAM size byte.
   ''' </summary>
   ''' <remarks>http://romhack.wikia.com/wiki/SNES_header</remarks>
   ''' <value>The RAM size byte.</value>
   Public ReadOnly Property RamSize As Byte
       Get
           Return Me.ramSizeB
       End Get
   End Property
   ''' <summary>
   ''' (backing field) The ROM size byte.
   ''' </summary>
   Private ramSizeB As Byte

   ''' <summary>
   ''' Gets or sets the country data.
   ''' </summary>
   ''' <remarks>http://romhack.wikia.com/wiki/SNES_header</remarks>
   ''' <value>The country data.</value>
   Public Property Country As CountryData
       Get
           Return New CountryData(Me.CountryCode)
       End Get
       Set(ByVal value As CountryData)
           Me.SetByte(Me.startAddressCountryCode, value.Code)
           Me.CountryCode = value.Code
       End Set
   End Property

   ''' <summary>
   ''' The country code.
   ''' </summary>
   Private Property CountryCode As Byte

   ''' <summary>
   ''' Gets or sets the license code.
   ''' </summary>
   ''' <remarks>http://romhack.wikia.com/wiki/SNES_header</remarks>
   ''' <value>The license code.</value>
   Public Property LicenseCode As Byte
       Get
           Return Me.licenseCodeB
       End Get
       Set(ByVal value As Byte)
           Me.SetByte(Me.startAddressLicenseCode, value)
           Me.licenseCodeB = value
       End Set
   End Property
   ''' <summary>
   ''' (backing field) The license code.
   ''' </summary>
   Private licenseCodeB As Byte

   ''' <summary>
   ''' Gets or sets the version number.
   ''' </summary>
   ''' <remarks>http://romhack.wikia.com/wiki/SNES_header</remarks>
   ''' <value>The version number.</value>
   Public Property VersionNumber As Byte
       Get
           Return Me.versionNumberB
       End Get
       Set(ByVal value As Byte)
           Me.SetByte(Me.startAddressVersionNumber, value)
           Me.versionNumberB = value
       End Set
   End Property
   ''' <summary>
   ''' (backing field) The version number.
   ''' </summary>
   Private versionNumberB As Byte

   ''' <summary>
   ''' Gets the checksum compliment.
   ''' </summary>
   ''' <remarks>http://romhack.wikia.com/wiki/SNES_header</remarks>
   ''' <value>The checksum compliment.</value>
   Public ReadOnly Property ChecksumCompliment As UShort
       Get
           Return Me.checksumComplimentB
       End Get
   End Property
   ''' <summary>
   ''' (backing field) The checksum compliment.
   ''' </summary>
   Private checksumComplimentB As UShort

   ''' <summary>
   ''' Gets the checksum.
   ''' </summary>
   ''' <remarks>http://romhack.wikia.com/wiki/SNES_header</remarks>
   ''' <value>The checksum.</value>
   Public ReadOnly Property Checksum As UShort
       Get
           Return Me.checksumB
       End Get
   End Property
   ''' <summary>
   ''' (backing field) The checksum.
   ''' </summary>
   Private checksumB As UShort

#End Region

#Region " Header Addresses "

   ' ********************************************************************************************************************
   ' NOTE:
   ' The reason for the variables that are commented-out is just because are unused, but could be helpful in the future.
   ' ********************************************************************************************************************

   ' ''' <summary>
   ' ''' The start address of a Lo-ROM header.
   ' ''' </summary>
   'Private ReadOnly loRomHeaderAddress As UShort = 32704

   ' ''' <summary>
   ' ''' The start address of a Hi-ROM header.
   ' ''' </summary>
   'Private ReadOnly hiRomHeaderAddress As UShort = 65472

   ''' <summary>
   ''' The start address of the ROM name.
   ''' </summary>
   Private ReadOnly startAddressName As Integer = 0

   ''' <summary>
   ''' The end address of the ROM name.
   ''' </summary>
   Private ReadOnly endAddressName As Integer = 20

   ''' <summary>
   ''' The start address of the ROM layout.
   ''' </summary>
   Private ReadOnly startAddressLayout As Integer = 21

   ' ''' <summary>
   ' ''' The end address of the ROM layout.
   ' ''' </summary>
   'Private ReadOnly endAddressLayout As Integer = 21

   ''' <summary>
   ''' The start address of the ROM cartridge type.
   ''' </summary>
   Private ReadOnly startAddressCartridgeType As Integer = 22

   ' ''' <summary>
   ' ''' The end address of the ROM cartridge type.
   ' ''' </summary>
   'Private ReadOnly endAddressCartridgeType As Integer = 22

   ''' <summary>
   ''' The start address of the ROM size (rom).
   ''' </summary>
   Private ReadOnly startAddressRomSize As Integer = 23

   ' ''' <summary>
   ' ''' The end address of the ROM size (rom).
   ' ''' </summary>
   'Private ReadOnly endAddressRomSize As Integer = 23

   ''' <summary>
   ''' The start address of the ROM size (ram).
   ''' </summary>
   Private ReadOnly startAddressRamSize As Integer = 24

   ' ''' <summary>
   ' ''' The end address of the ROM size (ram).
   ' ''' </summary>
   'Private ReadOnly endAddressRamSize As Integer = 24

   ''' <summary>
   ''' The start address of the ROM country code.
   ''' </summary>
   Private ReadOnly startAddressCountryCode As Integer = 25

   ' ''' <summary>
   ' ''' The end address of the ROM country code.
   ' ''' </summary>
   'Private ReadOnly endAddressCountryCode As Integer = 25

   ''' <summary>
   ''' The start address of the ROM license code.
   ''' </summary>
   Private ReadOnly startAddressLicenseCode As Integer = 26

   ' ''' <summary>
   ' ''' The end address of the ROM license code.
   ' ''' </summary>
   'Private ReadOnly endAddressLicenseCode As Integer = 26

   ''' <summary>
   ''' The start address of the ROM Version Number.
   ''' </summary>
   Private ReadOnly startAddressVersionNumber As Integer = 27

   ' ''' <summary>
   ' ''' The end address of the ROM Version Number.
   ' ''' </summary>
   'Private ReadOnly endAddresVersionNumber As Integer = 27

   ''' <summary>
   ''' The start address of the ROM checksum compliment.
   ''' </summary>
   Private ReadOnly startAddressChecksumCompliment As Integer = 28

   ''' <summary>
   ''' The end address of the ROM checksum compliment.
   ''' </summary>
   Private ReadOnly endAddressChecksumCompliment As Integer = 29

   ''' <summary>
   ''' The start address of the ROM checksum.
   ''' </summary>
   Private ReadOnly startAddressChecksum As Integer = 30

   ''' <summary>
   ''' The end address of the ROM checksum.
   ''' </summary>
   Private ReadOnly endAddressChecksum As Integer = 31

#End Region

#Region " Enumerations "

   ''' <summary>
   ''' Specifies a SNES ROM header type.
   ''' A headered ROM has SMC header and SNES header.
   ''' A headerless ROM has no SMC header, but still contains a SNES header.
   ''' Note that both a LoRom and HiRom images can be headered, or headerless.
   ''' <remarks>http://romhack.wikia.com/wiki/SNES_header</remarks>
   ''' </summary>
   Public Enum HeaderTypeEnum As Integer

       ''' <summary>
       ''' A headered SNES ROM.
       ''' The ROM contains an SMC header, and also contains an SNES header.
       ''' </summary>
       Headered = 0

       ''' <summary>
       ''' A headerless SNES ROM.
       ''' The ROM does not contains an SMC header, but contains an SNES header.
       ''' </summary>
       Headerless = 1

   End Enum

   ''' <summary>
   ''' Specifies a SNES ROM bank type.
   ''' <remarks>http://romhack.wikia.com/wiki/SNES_ROM_layout</remarks>
   ''' </summary>
   Public Enum BankTypeEnum As UShort

       ''' <summary>
       ''' A LoROM maps each ROM bank into the upper half (being addresses $8000 to $ffff) of each SNES bank,
       ''' starting with SNES bank $00, and starting again with SNES bank $80.
       ''' </summary>
       LoRom = 32704US

       ''' <summary>
       ''' A HiROM maps each ROM bank into the whole (being addresses $0000 to $ffff) of each SNES bank,
       ''' starting with SNES bank $40, and starting again with SNES bank $80.
       ''' </summary>
       HiRom = 65472US

   End Enum

   ''' <summary>
   ''' Specifies a SNES ROM cartridge type.
   ''' <remarks>http://romhack.wikia.com/wiki/SNES_ROM_layout</remarks>
   ''' </summary>
   Public Enum CartridgeTypeEnum As Byte

       ''' <summary>
       ''' A ROM without save-RAM.
       ''' </summary>
       NoSram0 = 0

       ''' <summary>
       ''' A ROM without save-RAM.
       ''' <remarks>I didn't fully verified this value...</remarks>
       ''' </summary>
       NoSram1 = 1

       ''' <summary>
       ''' A ROM with save-RAM.
       ''' </summary>
       Sram = 2

   End Enum

#End Region

#Region " Exceptions "

   ''' <summary>
   ''' Exception that is thrown when a SNES ROM has an invalid format.
   ''' </summary>
   <Serializable>
   Public NotInheritable Class InvalidRomFormatException : Inherits Exception

       ''' <summary>
       ''' Initializes a new instance of the <see cref="InvalidROMFormatException"/> class.
       ''' </summary>
       Public Sub New()
           MyBase.New("The SNES ROM image has an invalid format.")
       End Sub

       ''' <summary>
       ''' Initializes a new instance of the <see cref="InvalidROMFormatException"/> class.
       ''' </summary>
       ''' <param name="message">The message that describes the error.</param>
       Public Sub New(ByVal message As String)
           MyBase.New(message)
       End Sub

       ''' <summary>
       ''' Initializes a new instance of the <see cref="InvalidROMFormatException"/> class.
       ''' </summary>
       ''' <param name="message">The message that describes the error.</param>
       ''' <param name="inner">The inner exception.</param>
       Public Sub New(ByVal message As String, ByVal inner As Exception)
           MyBase.New(message, inner)
       End Sub

   End Class

#End Region

#Region " Types "

   ''' <summary>
   ''' Defines a SNES ROM country.
   ''' </summary>
   <Serializable>
   Public NotInheritable Class CountryData

#Region " Properties "

       ''' <summary>
       ''' Gets the region, which can de PAL or NTSC.
       ''' </summary>
       ''' <remarks>http://romhack.wikia.com/wiki/SNES_header</remarks>
       ''' <value>The country code.</value>
       Public ReadOnly Property Region As RegionTypeEnum
           Get
               Return Me.regionB
           End Get
       End Property
       ''' <summary>
       ''' (backing field) The region, which can de PAL or NTSC.
       ''' </summary>
       Private ReadOnly regionB As RegionTypeEnum

       ''' <summary>
       ''' Gets the country code.
       ''' </summary>
       ''' <value>The country code.</value>
       Public ReadOnly Property Code As Byte
           Get
               Return Me.codeB
           End Get
       End Property
       ''' <summary>
       ''' (backing field) The country code.
       ''' </summary>
       Private ReadOnly codeB As Byte

       ''' <summary>
       ''' Gets the country name.
       ''' </summary>
       ''' <value>The country name.</value>
       Public ReadOnly Property Name As String
           Get
               Return Me.nameB
           End Get
       End Property
       ''' <summary>
       ''' (backing field) The country name.
       ''' </summary>
       Private ReadOnly nameB As String

#End Region

#Region " Enumerations "

       ''' <summary>
       ''' Specifies a SNES ROM region type.
       ''' <remarks>http://romhack.wikia.com/wiki/SNES_header</remarks>
       ''' </summary>
       Public Enum RegionTypeEnum As Integer

           ''' <summary>
           ''' A PAL SNES ROM.
           ''' </summary>
           Pal = 0

           ''' <summary>
           ''' An NTSC SNES ROM.
           ''' </summary>
           Ntsc = 1

       End Enum

#End Region

#Region " Countries "

       ''' <summary>
       ''' The known ROM countries, based on country code from 0 to 13, so countrycode 0 = Japan, countrycode 1 = United States, and so on...
       ''' Unknown country codes are just unknown.
       ''' </summary>
       Private ReadOnly countryDict As New Dictionary(Of Integer, String) From
           {
               {0, "Japan"},
               {1, "United States"},
               {2, "Unknown"},
               {3, "Unknown"},
               {4, "Unknown"},
               {5, "Unknown"},
               {6, "Unknown"},
               {7, "Unknown"},
               {8, "Spain"},
               {9, "Unknown"},
               {10, "Unknown"},
               {11, "Unknown"},
               {12, "Unknown"},
               {13, "Unknown"}
           }

#End Region

#Region " Regions "

       ''' <summary>
       ''' The country codes for NTSC region.
       ''' <remarks>http://romhack.wikia.com/wiki/SMC_header</remarks>
       ''' </summary>
       Private ReadOnly ntscRegionCodes As Integer() =
           {0, 1, 13}

       ''' <summary>
       ''' The country codes for PAL region.
       ''' <remarks>http://romhack.wikia.com/wiki/SMC_header</remarks>
       ''' </summary>
       Private ReadOnly palRegionCodes As Integer() =
           {2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}

#End Region

#Region " Constructors "

       ''' <summary>
       ''' Initializes a new instance of the <see cref="CountryData"/> class.
       ''' </summary>
       ''' <param name="countryCode">The SNES ROM country code.</param>
       ''' <exception cref="ArgumentException">Invalid country code.;countryCode</exception>
       Public Sub New(ByVal countryCode As Byte)

           If Not (Me.ntscRegionCodes.Concat(Me.palRegionCodes)).Contains(countryCode) Then
               Throw New ArgumentException(message:="Invalid country code.", paramName:="countryCode")

           Else
               Me.codeB = countryCode
               Me.nameB = Me.countryDict(countryCode)

               ' Determine region.
               If Me.ntscRegionCodes.Contains(countryCode) Then
                   Me.regionB = RegionTypeEnum.Ntsc

               ElseIf Me.palRegionCodes.Contains(countryCode) Then
                   Me.regionB = RegionTypeEnum.Pal

               End If

           End If

       End Sub

       ''' <summary>
       ''' Prevents a default instance of the <see cref="CountryData"/> class from being created.
       ''' </summary>
       Private Sub New()
       End Sub

#End Region

   End Class

#End Region

#Region " Constructors "

   ''' <summary>
   ''' Prevents a default instance of the <see cref="SnesRom"/> class from being created.
   ''' </summary>
   Private Sub New()
   End Sub

   ''' <summary>
   ''' Initializes a new instance of the <see cref="SnesRom"/> class.
   ''' </summary>
   ''' <param name="romFilePath">The SNES ROM file path.</param>
   Public Sub New(ByVal romFilePath As String)

       Me.New(File.ReadAllBytes(romFilePath))

   End Sub

   ''' <summary>
   ''' Initializes a new instance of the <see cref="SnesRom"/> class.
   ''' </summary>
   ''' <param name="romData">The raw byte-data of the ROM file.</param>
   Public Sub New(ByVal romData As Byte())

       Me.rawDataB = romData

       Me.VerifyRomFormat()
       Me.VerifyBankType()
       Me.ReadHeader()

   End Sub

#End Region

#Region " Private Methods "

   ''' <summary>
   ''' Reads the ROM header to retrieve the header data.
   ''' </summary>
   Private Sub ReadHeader()

       ' Read range of bytes.
       Me.nameB = Encoding.ASCII.GetString(Me.GetBytes(Me.startAddressName, Me.endAddressName)).Trim

       ' Read single bytes.
       Me.layoutB = Me.GetByte(Me.startAddressLayout)
       Me.cartridgeTypeB = DirectCast(Me.GetByte(Me.startAddressCartridgeType), CartridgeTypeEnum)
       Me.romSizeB = Me.GetByte(Me.startAddressRomSize)
       Me.ramSizeB = Me.GetByte(Me.startAddressRamSize)
       Me.CountryCode = Me.GetByte(Me.startAddressCountryCode)
       Me.LicenseCode = Me.GetByte(Me.startAddressLicenseCode)
       Me.VersionNumber = Me.GetByte(Me.startAddressVersionNumber)

   End Sub

   ''' <summary>
   ''' Verifies the SNES ROM format.
   ''' </summary>
   ''' <exception cref="SnesRom.InvalidRomFormatException">The SNES ROM image has an invalid format.</exception>
   Private Sub VerifyRomFormat()

       If (Me.rawDataB.Length Mod 1024 = 512) Then
           Me.headerTypeB = HeaderTypeEnum.Headered

       ElseIf (Me.rawDataB.Length Mod 1024 = 0) Then
           Me.headerTypeB = HeaderTypeEnum.Headerless

       Else
           Throw New InvalidRomFormatException(message:="The SNES ROM image has an invalid format.")

       End If

   End Sub

   ''' <summary>
   ''' Verifies the SNES ROM bank type.
   ''' </summary>
   ''' <exception cref="Exception">Cannot recognize the bank type.</exception>
   Private Sub VerifyBankType()

       If Me.HeaderIsAt(BankTypeEnum.LoRom) Then
           Me.bankTypeB = BankTypeEnum.LoRom

       ElseIf Me.HeaderIsAt(BankTypeEnum.HiRom) Then
           Me.bankTypeB = BankTypeEnum.HiRom

       Else
           Throw New Exception(message:="Cannot recognize the bank type.")

       End If

   End Sub

   ''' <summary>
   ''' Verifies the checksum.
   ''' </summary>
   ''' <remarks>
   ''' Offset 0x07FC0 in a headerless LoROM image (LoROM rom sin smc header)
   ''' Offset 0x0FFC0 in a headerless HiROM image (HiROM rom sin smc header)
   ''' </remarks>
   ''' <returns><c>true</c> if checksum is ok, <c>false</c> otherwise.</returns>
   Private Function VerifyChecksum() As Boolean

       If Me.HeaderType = HeaderTypeEnum.Headered Then
           Me.headerLocationB += 512
       End If

       Me.checksumComplimentB = BitConverter.ToUInt16(Me.GetBytes(Me.startAddressChecksumCompliment, Me.endAddressChecksumCompliment), startIndex:=0)

       Me.checksumB = BitConverter.ToUInt16(Me.GetBytes(Me.startAddressChecksum, Me.endAddressChecksum), startIndex:=0)

       Return CUShort(Me.Checksum Xor Me.ChecksumCompliment).Equals(UShort.MaxValue)

   End Function

   ''' <summary>
   ''' Determines whether the ROM header is in the specified address.
   ''' </summary>
   ''' <param name="address">The address.</param>
   ''' <returns><c>true</c> if the ROM header is in the specified address, <c>false</c> otherwise.</returns>
   Private Function HeaderIsAt(ByVal address As UShort) As Boolean

       Me.headerLocationB = address
       Return Me.VerifyChecksum()

   End Function

   ''' <summary>
   ''' Gets the specified byte from the raw byte-data.
   ''' </summary>
   ''' <param name="address">The address.</param>
   ''' <returns>The specified byte from the raw byte-data.</returns>
   Private Function GetByte(ByVal address As Integer) As Byte

       Return Buffer.GetByte(array:=Me.RawData,
                             index:=Me.HeaderLocation + address)

   End Function

   ''' <summary>
   ''' Gets the specified range of bytes from the raw byte-data.
   ''' </summary>
   ''' <param name="from">From address.</param>
   ''' <param name="to">To address.</param>
   ''' <returns>The specified bytes from the raw byte-data.</returns>
   Private Function GetBytes(ByVal from As Integer,
                             ByVal [to] As Integer) As Byte()

       Return Me.RawData.Skip(Me.HeaderLocation + from).Take(([to] - from) + 1).ToArray()

   End Function

   ''' <summary>
   ''' Replaces a single byte in the raw byte-data, with the specified data.
   ''' </summary>
   ''' <param name="address">the address.</param>
   ''' <param name="data">The byte-data.</param>
   Private Sub SetByte(ByVal address As Integer,
                      ByVal data As Byte)

       Buffer.SetByte(array:=Me.rawDataB,
                      index:=Me.HeaderLocation + address,
                      value:=data)

   End Sub

   ''' <summary>
   ''' Replaces the specified range of bytes in the raw byte-data, with the specified data.
   ''' </summary>
   ''' <param name="from">From address.</param>
   ''' <param name="to">To address.</param>
   ''' <param name="data">The byte-data.</param>
   ''' <exception cref="ArgumentException">The byte-length of the specified data differs from the byte-length to be replaced;data</exception>
   Private Sub SetBytes(ByVal from As Integer,
                       ByVal [to] As Integer,
                       ByVal data As Byte())

       If data.Length <> (([to] - from) + 1) Then
           Throw New ArgumentException("The byte-length of the specified data differs from the byte-length to be replaced.", "data")

       Else
           Buffer.BlockCopy(src:=data, srcOffset:=0,
                            dst:=Me.rawDataB, dstOffset:=Me.HeaderLocation + from,
                            count:=([to] - from) + 1)

       End If

   End Sub

   ''' <summary>
   ''' Sets the ROM name.
   ''' </summary>
   ''' <param name="name">The ROM name.</param>
   ''' <exception cref="ArgumentNullException">name</exception>
   ''' <exception cref="ArgumentException">The name should contain 21 or less characters;name.</exception>
   Private Sub SetName(ByVal name As String)

       Dim fixedNameLength As Integer = (Me.endAddressName - Me.startAddressName) + 1

       If String.IsNullOrEmpty(name) Then
           Throw New ArgumentNullException(paramName:="name")

       ElseIf (name.Length > fixedNameLength) Then
           Throw New ArgumentException(message:="The name should contain 21 or less characters.", paramName:="name")

       Else
           ' fill with spaces up to 21 character length.
           name = name.PadRight(totalWidth:=fixedNameLength, paddingChar:=" "c)

           Me.SetBytes(Me.startAddressName, Me.endAddressName, Encoding.ASCII.GetBytes(name))

       End If

   End Sub

#End Region

#Region " Public Methods "

   ''' <summary>
   ''' Save the ROM changes to the specified file path.
   ''' </summary>
   ''' <param name="filePath">The ROM file path.</param>
   ''' <param name="replace">
   ''' If set to <c>true</c>, then replaces any existing file,
   ''' otherwise, throws an <see cref="IOException"/> exception if file already exists.
   ''' </param>
   ''' <exception cref="IOException">The destination file already exists.</exception>
   Public Sub Save(ByVal filePath As String, ByVal replace As Boolean)

       If Not replace AndAlso File.Exists(filePath) Then
           Throw New IOException(message:="The destination file already exists.")

       Else
           Try
               File.WriteAllBytes(filePath, Me.rawDataB)

           Catch ex As Exception
               Throw

           End Try

       End If

   End Sub

#End Region

End Class





Ejemplo para leer los datos de una ROM:
Código (vbnet) [Seleccionar]
Dim romDump As New SnesRom("C:\ROM.smc")
' Or...
' Dim romDump As New SnesRom(File.ReadAllBytes("C:\ROM.smc"))

Dim sb As New StringBuilder
With sb
   .AppendLine(String.Format("Name...............: {0}", romDump.Name))
   .AppendLine(String.Format("Bank Type..........: {0}", romDump.BankType.ToString))
   .AppendLine(String.Format("Cartridge Type.....: {0}", romDump.CartridgeType.ToString.ToUpper))
   .AppendLine(String.Format("Checksum...........: {0}", romDump.Checksum.ToString))
   .AppendLine(String.Format("Checksum Compliment: {0}", romDump.ChecksumCompliment.ToString))
   .AppendLine(String.Format("Country Region.....: {0}", romDump.Country.Region.ToString.ToUpper))
   .AppendLine(String.Format("Country Code.......: {0}", romDump.Country.Code.ToString))
   .AppendLine(String.Format("Country Name.......: {0}", romDump.Country.Name))
   .AppendLine(String.Format("Header Type........: {0}", romDump.HeaderType.ToString))
   .AppendLine(String.Format("Layout.............: {0}", romDump.Layout.ToString))
   .AppendLine(String.Format("License Code.......: {0}", romDump.LicenseCode.ToString))
   .AppendLine(String.Format("RAM Size...........: {0}", romDump.RamSize.ToString))
   .AppendLine(String.Format("ROM Size...........: {0}", romDump.RomSize.ToString))
   .AppendLine(String.Format("Version Number.....: {0}", romDump.VersionNumber.ToString))
End With

Clipboard.SetText(sb.ToString) : MessageBox.Show(sb.ToString)


Resultado de ejecución de la lectura de una ROM:
Name...............: THE LEGEND OF ZELDA
Bank Type..........: LoRom
Cartridge Type.....: SRAM
Checksum...........: 44813
Checksum Compliment: 20722
Country Region.....: NTSC
Country Code.......: 1
Country Name.......: United States
Header Type........: Headered
Layout.............: 32
License Code.......: 1
RAM Size...........: 3
ROM Size...........: 10
Version Number.....: 0


Ejemplo para modificar una ROM:
Código (vbnet) [Seleccionar]
Dim romDump As New SnesRom("C:\ROM.smc")
' Or...
' Dim romDump As New SnesRom(File.ReadAllBytes("C:\Rom.smc"))

With romDump
   .Name = "Elektrozoider"
   .Country = New SnesRom.CountryData(countryCode:=8) ' Spain.
   .VersionNumber = CByte(3)
   .Save("C:\Hacked.smc", replace:=True)
End With
Título: Re: Leer una clase en un formulario Windows de Visual C#
Publicado por: Meta en 10 Junio 2015, 20:08 PM
Hola:

Fuerte código. ;)

Con estas dos Web he intentado traducirloa C# y me dice:
http://www.developerfusion.com/tools/convert/vb-to-csharp/?batchId=37f5bff7-8541-40f9-aa53-a9e112a0aac2
CitarAn error occured converting your code, probably due to a syntax error: -- line 577 col 84: "{" expected

En esta otra Web me dice.
http://converter.telerik.com/
CitarCONVERSION ERROR: Code could not be converted. Details:

-- line 577 col 84: "{" expected

Please check for any errors in the original code and try again.


Muy pero que muy, muy, muy y muy buen trabajo.

Lo del código del país, lo poco he encontra está aquí.
http://romhack.wikia.com/wiki/SNES_header
http://romhack.wikia.com/wiki/SMC_header

No se si el código del país con teléfonos tiene algo que ver.
http://personas.entel.cl/PortalPersonas/appmanager/entelpcs/personas?_nfpb=true&_pageLabel=P4400216791251672510516

Esto no tiene nada que ver, pero puede dar ideas para algo.
http://www.elotrolado.net/hilo_acerca-de-los-codigos-de-los-juegos-de-super-nintendo_999526

Más datos referente a código de país de la ROM.
http://es.wikipedia.org/wiki/Imagen_ROM

Seguiré buscando...

Por cierto, para leer SmcHeader, no lo tenía en public, ajjajajajaa. Ahora si lo lee.
Código (csharp) [Seleccionar]
textBox_SmcHeader.Text = VARIABLE.SmcHeader ? "True" : "False";

Voy acabar los demás. Y la parte que quiero guardar, es la del título del juego, para poner información.

Saludos.
Título: Re: Leer una clase en un formulario Windows de Visual C#
Publicado por: Eleкtro en 10 Junio 2015, 20:25 PM
Cita de: Meta en 10 Junio 2015, 20:08 PMhe intentado traducirloa C# y me dice:

El motor/librería NRefactory que utilizan practicamente todos los traductores, es bastante estricto con los saltos de linea en ciertas partes, los cuales si que están permitidos en la IDE.

Debes escribir el bracket despues del keyword From.

Es decir, de esto:
Citar
Código (vbnet,1,2) [Seleccionar]
       Private ReadOnly countryDict As New Dictionary(Of Integer, String) From
           {
               {0, "Japan"},
               {1, "United States"},
               {2, "Unknown"},
               {3, "Unknown"},
               {4, "Unknown"},
               {5, "Unknown"},
               {6, "Unknown"},
               {7, "Unknown"},
               {8, "Spain"},
               {9, "Unknown"},
               {10, "Unknown"},
               {11, "Unknown"},
               {12, "Unknown"},
               {13, "Unknown"}
           }

A esto otro:
Código (vbnet,1) [Seleccionar]
       Private ReadOnly countryDict As New Dictionary(Of Integer, String) From {
               {0, "Japan"},
               {1, "United States"},
               {2, "Unknown"},
               {3, "Unknown"},
               {4, "Unknown"},
               {5, "Unknown"},
               {6, "Unknown"},
               {7, "Unknown"},
               {8, "Spain"},
               {9, "Unknown"},
               {10, "Unknown"},
               {11, "Unknown"},
               {12, "Unknown"},
               {13, "Unknown"}
           }





Cita de: Meta en 10 Junio 2015, 20:08 PMMuy pero que muy, muy, muy y muy buen trabajo.

Gracias. Alguien debería donarme unos eurillos a mi paypal :silbar:.

Saludos!
Título: Re: Leer una clase en un formulario Windows de Visual C#
Publicado por: Meta en 10 Junio 2015, 21:38 PM
Hola:

Hice esto rápido, ya lo puliré.
Código (csharp) [Seleccionar]
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using System.IO; // No olvidar.

namespace ROM_SNES
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                FileInfo Archivo = new FileInfo(openFileDialog1.FileName);
                SnesKit.RomDump VARIABLE = new SnesKit.RomDump(File.ReadAllBytes(openFileDialog1.FileName.ToString()));
                textBox_Nombre_ruta_archivo.Text = openFileDialog1.FileName.ToString(); // Muestra la ruta del archivo.
                textBox_Name.Text = VARIABLE.Name;
                textBox_Layout.Text = string.Format("{0:X}", VARIABLE.Layout);
                textBox_CartridgeType.Text = string.Format("{0:X}", VARIABLE.CartridgeType);
                textBox_RomSize.Text = string.Format("{0:X}", VARIABLE.RomSize);
                textBox_RamSize.Text = string.Format("{0:X}", VARIABLE.RamSize);
                textBox_CountryCode.Text = string.Format("{0:X}", VARIABLE.CountryCode);
                textBox_LicenseCode.Text = string.Format("{0:X}", VARIABLE.LicenseCode);
                textBox_VersionNumber.Text = string.Format("{0:X}", VARIABLE.VersionNumber);
                textBox_BankType.Text = VARIABLE.BankType.ToString();
                textBox_Checksum.Text = string.Format("{0:X}", VARIABLE.Checksum);
                textBox_ChecksumCompliment.Text = string.Format("{0:X}", VARIABLE.ChecksumCompliment);
                textBox_SmcHeader.Text = VARIABLE.SmcHeader ? "True" : "False";
                textBox_HeaderLocation.Text = string.Format("{0:X}", VARIABLE.HeaderLocation);
                textBox_MB.Text = string.Format("{0:N0}", (Archivo.Length / 1024f) / 1024f); // Resultado 4 MB.
                textBox_KB.Text = string.Format("{0:N0}", (Archivo.Length / 1024f)); // 4.907 KB.
                textBox_Bytes.Text = string.Format("{0:N0}", Archivo.Length); // 4.194.816 B o Bytes.
                textBox_Mbit.Text = string.Format("{0:N0}", ((Archivo.Length / 1024f) / 1024f) * 8); // Mega bits.
            }
        }
    }
}


Había que poner variables en public para que me hiciera caso, el que no logro es el textbox addr, no se como poner esa variable en public.

Muestro la imagen de abajo.

(https://social.msdn.microsoft.com/Forums/getfile/667989)

1) Como puedes ver arriba, en el Cuadro 3 azul, en el textBox en MB pone 4. ¿Cómo hago que se vea el subfijo de esta manera?

En vez de 4 MB que muestre 4.00 MB.

2) En el Cuadro 4 amarillo, en el textBox "Nombre del archivo". Cuando abro un archivo en el botón "Arbrir archivo" en eltextBox "Ruta del archivo" se ve la ruta y el nombre del archivo. En el textBox "Nombre del archivo". ¿Cómo hago para que vea su nombre?

He estado mirando los formatos y no me sale.

Saludos.
Título: Re: Leer una clase en un formulario Windows de Visual C#
Publicado por: Eleкtro en 10 Junio 2015, 22:23 PM
Cita de: Meta en 10 Junio 2015, 21:38 PM

1)¿Cómo hago que se vea el subfijo de esta manera?
En vez de 4 MB que muestre 4.00 MB.

Debes usar la extensión ToString para convertir el valor numérico (repito, numérico, no String) a String, dándole el formato númerico al string, donde debes usar un formato que añada una precisión de 2 decimales.

Código (vbnet) [Seleccionar]
4.ToString("formato específico")

Es muy sencillo lo que quieres hacer, lee aquí para conocer la sintaxis del formato numérico, no te costará nada encontrar los caracteres que debes para el formato que necesitas darle:
Custom Numeric Format Strings - MSDN (https://msdn.microsoft.com/en-us/library/0c899ak8%28v=vs.110%29.aspx)




Cita de: Meta en 10 Junio 2015, 21:38 PM2) En el Cuadro 4 amarillo, en el textBox "Nombre del archivo". Cuando abro un archivo en el botón "Arbrir archivo" en eltextBox "Ruta del archivo" se ve la ruta y el nombre del archivo. En el textBox "Nombre del archivo". ¿Cómo hago para que vea su nombre?

Lee los métodos de la Class System.IO.Path, tiene un método para devolver el nombre de archivo de una ruta de archivo. Esto tampoco tiene pérdida.
Path Methods (System.IO) - MSDN (https://msdn.microsoft.com/en-us/library/system.io.path_methods%28v=vs.110%29.aspx)

PD: De todas formas no creo que te costase nada buscar en Google "C# get filename" antes de preguntarlo... seguro que saldran miles de resultados por que es muy básico.

Saludos!
Título: Re: Leer una clase en un formulario Windows de Visual C#
Publicado por: Meta en 11 Junio 2015, 09:55 AM
Hola:

Hay algo de aquí que no me cuadra.
http://romhack.wikia.com/wiki/SNES_header

Donde pone:
Código (csharp) [Seleccionar]
ROM and RAM size bytes ($ffd7 and $ffd8) Edit

Byte $ffd7 indicates the amount of ROM in the cartridge; byte $ffd8 indicates the amount of RAM in the cartridge (excluding the RAM in the SNES system). Both bytes use the same scale.

    $00 => no RAM
    $01 => $800 bytes == 2 kilobytes, amount of RAM in Super Mario World
    $02 => $1000 bytes == 4 kilobytes
    $03 => $2000 bytes == 8 kilobytes
    $04 => $4000 bytes == 16 kilobytes
    $05 => $8000 bytes == 32 kilobytes, amount of RAM in Mario Paint
    $06 => $10000 bytes == 64 kilobytes
    $07 => $20000 bytes == 128 kilobytes, amount of RAM in Dezaemon - Kaite Tsukutte Asoberu
    $08 => $40000 bytes == 256 kilobytes, minimum for ROM
    $09 => $80000 bytes == 512 kilobytes, amount of ROM in Super Mario World
    $0a => $100000 bytes == 1 megabyte, amount of ROM in Mario Paint
    $0b => $200000 bytes == 2 megabytes
    $0c => $400000 bytes == 4 megabytes


Según tengo entendido, los valores de la ROM y la RAM son los mismos. Me pasa con cualquier juego. A mi me dan valores diferentes. Fijarse en la imagen de abajo.
(http://www.subeimagenes.com/img/re2-1347002.png)

¿Qué opinas?

Saludos.

Título: Re: Leer una clase en un formulario Windows de Visual C#
Publicado por: Eleкtro en 11 Junio 2015, 15:27 PM
Cita de: Meta en 11 Junio 2015, 09:55 AM¿Qué opinas?

No quiero parecer arrogante, pero opino que no deberías manejar algo que no entiendes ...y encima haciendo copy/pastes.

Solo has tenido una comprensión incorrecta de las palabras que pone en esa documentación. El tamaño de la memoria de solo lectura (ROM) difiere de la memoria RAM, busca las definiciones de ambas para comprender. La wikipedia está para algo.

Primero deberías aprender lo que te falta por aprender del lenguaje, y de los conceptos que necesites aprender para llevar a cabo esa tarea (aunque yo tampoco soy ningún erudito en el entendimiento de las especificaciones del formato de los cartuchos ROM de SNES ni de la lectura y escritura de offsets), y luego ya, cuando te veas más capaz, te pones a hacer un lector de cabeceras para "X" formato.




Dicho esto, no todo iba a ser malo, he actualizado y mejorado el código fuente que publiqué en la página anterior para añadirle toda la información que faltaba (y más), gracias a las especificaciones que encontré en esta página:
http://softpixel.com/~cwright/sianse/docs/Snesrom.txt
y a esta aplicación para comprobar los resultados de mis modificaciones:
http://www.zophar.net/utilities/snesaud/snes-explorer.html

Ahora el código está mucho mejor, y con algunas funcionalidades de escritura más, aunque sigue faltando algún que otro detalle del que me cuesta encontrar documentación.

Aunque no lo vayas a usar, de todas maneras lo comparto en este hilo por si a otra persona le viene bien esta ayuda en VB.Net:

Código fuente:
http://pastebin.com/JMUEdWrK

Ejemplo de uso para la lectura:
Código (vbnet) [Seleccionar]
Dim romDump As New SnesRom("C:\ROM.smc")
' Or...
' Dim romDump As New SnesRom(File.ReadAllBytes("C:\ROM.smc"))

Dim sb As New StringBuilder
With sb
   .AppendLine(String.Format("Name..................: {0}", romDump.Name))
   .AppendLine(String.Format("Bank Type.............: {0}", romDump.BankType.ToString))
   .AppendLine(String.Format("Cartridge Type........: {0}", romDump.CartridgeType.ToString.ToUpper.Replace("_", "/")))
   .AppendLine(String.Format("Checksum..............: {0}", String.Format("0x{0}", Convert.ToString(CInt(romDump.Checksum), toBase:=16).ToUpper)))
   .AppendLine(String.Format("Checksum Complement...: {0}", String.Format("0x{0}", Convert.ToString(CInt(romDump.ChecksumComplement), toBase:=16).ToUpper)))
   .AppendLine(String.Format("Country Code..........: {0}", romDump.Country.Code.ToString))
   .AppendLine(String.Format("Country Name..........: {0}", romDump.Country.Name))
   .AppendLine(String.Format("Country Region........: {0}", romDump.Country.Region.ToString.ToUpper))
   .AppendLine(String.Format("Header Type (SMC).....: {0}", romDump.HeaderType.ToString))
   .AppendLine(String.Format("Layout................: {0}", romDump.Layout.ToString))
   .AppendLine(String.Format("License Code/Name.....: {0}", romDump.LicenseCode.ToString))
   .AppendLine(String.Format("ROM Size..............: {0} MBits", romDump.RomSize.ToString.Substring(1, romDump.RomSize.ToString.LastIndexOf("M") - 2)).Replace("_or_", "/"))
   .AppendLine(String.Format("RAM Size..............: {0} KBits", romDump.RamSize.ToString.Substring(1, romDump.RamSize.ToString.LastIndexOf("K") - 2)))
   .AppendLine(String.Format("Version Number........: 1.{0}", romDump.Version.ToString))
End With

Clipboard.SetText(sb.ToString) : MessageBox.Show(sb.ToString)


Resultado de ejecución de la lectura:
Name..................: SUPER MARIOWORLD
Bank Type.............: LoRom
Cartridge Type........: ROM/SRAM
Checksum..............: 0xA0DA
Checksum Complement...: 0x5F25
Country Code..........: 1
Country Name..........: United States
Country Region........: NTSC
Header Type (SMC).....: Headered
Layout................: 32
License Code/Name.....: Nintendo
ROM Size..............: 8 MBits
RAM Size..............: 16 KBits
Version Number........: 1.0


Ejemplo de uso para la escritura:
Código (vbnet) [Seleccionar]
Dim romDump As New SnesRom("C:\ROM.smc")
' Or...
' Dim romDump As New SnesRom(File.ReadAllBytes("C:\ROM.smc"))

With romDump
   .Name = "Elektrocitos"
   .Version = 1
   .Country = New SnesRom.CountryData(countryCode:=0) ' Japan.
   .LicenseCode = SnesRom.LicenseCodeEnum.Taito
   .RomSize = SnesRom.ROMSizeEnum._4_Mbits
   .RamSize = SnesRom.SRAMSizeEnum._256_Kbits
   .Save("C:\Elektron.smc", replace:=True)
End With


Saludos!
Título: Re: Leer una clase en un formulario Windows de Visual C#
Publicado por: Meta en 11 Junio 2015, 23:25 PM
Hola:

Impresionante, pedazo trabajo. JAjaja.

Te iba poner el mismo documento pero en otra Web.
http://www.emulatronia.com/doctec/consolas/snes/sneskart.html

Sacada de aqui.
http://www.emulatronia.com/consolas/doctec/dt-snes.htm

En este se explica mejor las cabeceras.
http://en.m.wikibooks.org/wiki/Super_NES_Programming/SNES_memory_map

Aquí información de SNES de unas 800 páginas, descarga de 24 MB.
http://www.romhacking.net/documents/226/

Una curiosidad. Por ejemplo, cuando vayas a modificar un dato, que es el único ASCII que hay legible en toda la ROM, es decir, el título del juego, si lo modificas, también en otra área de la ROM, se cambia el Checksum.

¿Cómo lo solucionas?

Saludos.


Edito:
Hice por ahora hasta aquí y esto hasta las ******************************** de colocar compañías.
Código (csharp) [Seleccionar]
                if (Codigo_Licencia == "0")
                {
                    textBox_Codigo_Licencia_2.Text = "Código de Licencia inválida";
                }
                else if (Codigo_Licencia == "1")
                {
                    textBox_Codigo_Licencia_2.Text = "Nintendo";
                }
                else if (Codigo_Licencia == "5")
                {
                    textBox_Codigo_Licencia_2.Text = "Zamuse";
                }
                else if (Codigo_Licencia == "8")
                {
                    textBox_Codigo_Licencia_2.Text = "Capcom";
                }
                else if (Codigo_Licencia == "9")
                {
                    textBox_Codigo_Licencia_2.Text = "HOT B";
                }
                else if (Codigo_Licencia == "A")
                {
                    textBox_Codigo_Licencia_2.Text = "Jaleco";
                }
                else if (Codigo_Licencia == "B")
                {
                    textBox_Codigo_Licencia_2.Text = "STORM (Sales Curve) (1)";
                }
                else if (Codigo_Licencia == "F")
                {
                    textBox_Codigo_Licencia_2.Text = "Mebio Software";
                }
                else if (Codigo_Licencia == "12")
                {
                    textBox_Codigo_Licencia_2.Text = "Gremlin Graphics";
                }
                else if (Codigo_Licencia == "15")
                {
                    textBox_Codigo_Licencia_2.Text = "COBRA Team";
                }
                else if (Codigo_Licencia == "16")
                {
                    textBox_Codigo_Licencia_2.Text = "Human/Field";
                }
                else if (Codigo_Licencia == "18")
                {
                    textBox_Codigo_Licencia_2.Text = "Hudson Soft";
                }
                else if (Codigo_Licencia == "1A")
                {
                    textBox_Codigo_Licencia_2.Text = "Yanoman";
                }
                else if (Codigo_Licencia == "1C")
                {
                    textBox_Codigo_Licencia_2.Text = "Tecmo (1)";
                }
                else if (Codigo_Licencia == "1E")
                {
                    textBox_Codigo_Licencia_2.Text = "Forum";
                }
                else if (Codigo_Licencia == "1F")
                {
                    textBox_Codigo_Licencia_2.Text = "Park Place Productions / VIRGIN";
                }
                else if (Codigo_Licencia == "21")
                {
                    textBox_Codigo_Licencia_2.Text = "Tokai Engeneering (SUNSOFT?)";
                }
                else if (Codigo_Licencia == "22")
                {
                    textBox_Codigo_Licencia_2.Text = "POW";
                }
                else if (Codigo_Licencia == "23")
                {
                    textBox_Codigo_Licencia_2.Text = "Loriciel / Micro World";
                }
                else if (Codigo_Licencia == "28")
                {
                    textBox_Codigo_Licencia_2.Text = "Kemco (1)";
                }
                else if (Codigo_Licencia == "29")
                {
                    textBox_Codigo_Licencia_2.Text = "Seta Co.,Ltd.";
                }
                else if (Codigo_Licencia == "2D")
                {
                    textBox_Codigo_Licencia_2.Text = "Visit Co.,Ltd.";
                }
                else if (Codigo_Licencia == "53")
                {
                    textBox_Codigo_Licencia_2.Text = "HECT";
                }
                else if (Codigo_Licencia == "3D")
                {
                    textBox_Codigo_Licencia_2.Text = "Loriciel";
                }
                else if (Codigo_Licencia == "3F")
                {
                    textBox_Codigo_Licencia_2.Text = "Seika Corp.";
                }
                else if (Codigo_Licencia == "40")
                {
                    textBox_Codigo_Licencia_2.Text = "UBI Soft";
                }
                else if (Codigo_Licencia == "47")
                {
                    textBox_Codigo_Licencia_2.Text = "Spectrum Holobyte";
                }
                else if (Codigo_Licencia == "49")
                {
                    textBox_Codigo_Licencia_2.Text = "Irem";
                }
                else if (Codigo_Licencia == "4B")
                {
                    textBox_Codigo_Licencia_2.Text = "Raya Systems/Sculptured Software";
                }
                else if (Codigo_Licencia == "4C")
                {
                    textBox_Codigo_Licencia_2.Text = "Renovation Pruducts";
                }
                else if (Codigo_Licencia == "4D")
                {
                    textBox_Codigo_Licencia_2.Text = "Malibu Games (T*HQ Inc.) / Black Pearl";
                }
                else if (Codigo_Licencia == "4F")
                {
                    textBox_Codigo_Licencia_2.Text = "U.S. Gold";
                }
                else if (Codigo_Licencia == "50")
                {
                    textBox_Codigo_Licencia_2.Text = "Absolute Entertainment";
                }
                else if (Codigo_Licencia == "51")
                {
                    textBox_Codigo_Licencia_2.Text = "Acclaim";
                }
                else if (Codigo_Licencia == "52")
                {
                    textBox_Codigo_Licencia_2.Text = "Activision";
                }
                else if (Codigo_Licencia == "53")
                {
                    textBox_Codigo_Licencia_2.Text = "American Sammy";
                }
                else if (Codigo_Licencia == "54")
                {
                    textBox_Codigo_Licencia_2.Text = "GameTek";
                }
                else if (Codigo_Licencia == "55")
                {
                    textBox_Codigo_Licencia_2.Text = "Hi Tech";
                }
                else if (Codigo_Licencia == "56")
                {
                    textBox_Codigo_Licencia_2.Text = "LJN Toys";
                }
                else if (Codigo_Licencia == "5A")
                {
                    textBox_Codigo_Licencia_2.Text = "Mindscape";
                }
                else if (Codigo_Licencia == "5D")
                {
                    textBox_Codigo_Licencia_2.Text = "Technos Japan Corp. (Tradewest)";
                }
                else if (Codigo_Licencia == "5F")
                {
                    textBox_Codigo_Licencia_2.Text = "American Softworks Corp.";
                }
                else if (Codigo_Licencia == "60")
                {
                    textBox_Codigo_Licencia_2.Text = "Titus";
                }
                else if (Codigo_Licencia == "61")
                {
                    textBox_Codigo_Licencia_2.Text = "Virgin Games";
                }
                else if (Codigo_Licencia == "62")
                {
                    textBox_Codigo_Licencia_2.Text = "Maxis";
                }
                else if (Codigo_Licencia == "67")
                {
                    textBox_Codigo_Licencia_2.Text = "Ocean";
                }


Aún me queda mucho y cansa psicológicamente.  ;D

Me salen juego con el valor 33 Hex. En la lista de abajo de tu enlace, no está precismamente esa compañía.

Código (csharp) [Seleccionar]
LICENSE       : 1 BYTE
     0 <Invalid License Code>
     1 Nintendo
     5 Zamuse
     8 Capcom
     9 HOT B
    10 Jaleco
    11 STORM (Sales Curve) (1)
    15 Mebio Software
    18 Gremlin Graphics
    21 COBRA Team
    22 Human/Field
    24 Hudson Soft
    26 Yanoman
    28 Tecmo (1)
    30 Forum
    31 Park Place Productions / VIRGIN
    33 Tokai Engeneering (SUNSOFT?)
    34 POW
    35 Loriciel / Micro World
    38 Enix
    40 Kemco (1)
    41 Seta Co.,Ltd.
    45 Visit Co.,Ltd.
    53 HECT
    61 Loriciel
    64 Seika Corp.
    65 UBI Soft
    71 Spectrum Holobyte
    73 Irem
    75 Raya Systems/Sculptured Software
    76 Renovation Pruducts
    77 Malibu Games (T*HQ Inc.) / Black Pearl
    79 U.S. Gold
    80 Absolute Entertainment
    81 Acclaim
    82 Activision
    83 American Sammy
    84 GameTek
    85 Hi Tech
    86 LJN Toys
    90 Mindscape
    93 Technos Japan Corp. (Tradewest)
    95 American Softworks Corp.
    96 Titus
    97 Virgin Games
    98 Maxis
   103 Ocean
   105 Electronic Arts
   107 Laser Beam
   110 Elite
   111 Electro Brain
   112 Infogrames
   113 Interplay
   114 LucasArts
   115 Sculptured Soft
   117 STORM (Sales Curve) (2)
   120 THQ Software
   121 Accolade Inc.
   122 Triffix Entertainment
   124 Microprose
   127 Kemco (2)
   130 Namcot/Namco Ltd. (1)
   132 Koei/Koei! (second license?)
   134 Tokuma Shoten Intermedia
   136 DATAM-Polystar
   139 Bullet-Proof Software
   140 Vic Tokai
   143 I'Max
   145 CHUN Soft
   146 Video System Co., Ltd.
   147 BEC
   151 Kaneco
   153 Pack in Video
   154 Nichibutsu
   155 TECMO (2)
   156 Imagineer Co.
   160 Wolf Team
   164 Konami
   165 K.Amusement
   167 Takara
   169 Technos Jap. ????
   170 JVC
   172 Toei Animation
   173 Toho
   175 Namcot/Namco Ltd. (2)
   177 ASCII Co. Activison
   178 BanDai America
   180 Enix
   182 Halken
   186 Culture Brain
   187 Sunsoft
   188 Toshiba EMI/System Vision
   189 Sony (Japan) / Imagesoft
   191 Sammy
   192 Taito
   194 Kemco (3) ????
   195 Square
   196 NHK
   197 Data East
   198 Tonkin House
   200 KOEI
   202 Konami USA
   205 Meldac/KAZe
   206 PONY CANYON
   207 Sotsu Agency
   209 Sofel
   210 Quest Corp.
   211 Sigma
   214 Naxat
   216 Capcom Co., Ltd. (2)
   217 Banpresto
   219 Hiro
   221 NCS
   222 Human Entertainment
   223 Ringler Studios
   224 K.K. DCE / Jaleco
   226 Sotsu Agency
   228 T&ESoft
   229 EPOCH Co.,Ltd.
   231 Athena
   232 Asmik
   233 Natsume
   234 King/A Wave
   235 Atlus
   236 Sony Music
   238 Psygnosis / igs
   243 Beam Software
   244 Tec Magik
   255 Hudson Soft


Por si alguien lo sabe, lo indica.

Gracias por todo.
Título: Re: Leer una clase en un formulario Windows de Visual C#
Publicado por: Eleкtro en 12 Junio 2015, 12:51 PM
Cita de: Meta en 11 Junio 2015, 23:25 PM¿Cómo lo solucionas?

No llego a comprender cómo se computa el Checksum.

De todas formas tampoco le doy ningún interés, ya que el checksum es solo un indicador, un bad checksum no afecta al comportamiento del juego.



Cita de: Meta en 11 Junio 2015, 23:25 PMEdito:
Hice por ahora hasta aquí y esto hasta las ******************************** de colocar compañías.

Lo que estás haciendo, aparte de no ser nada práctico, son malas prácticas de programación,
¿en que momento se te ocurre que la mejor solución es ponerte a escribir una a una las +120 condicionales?  :-\,
¿para que tienes a tu disposición las Classes/Types de .Net Framework si no las usas?, ¿para que estás programando en C#?.

Existe una cosa que se llama Diccionarios (Dictionary) entre otros muchos tipos de objetos que puedes utilizar, como listas, tuplas, arrays dimensionales, arrays escalonados (jagged array), etc, o tu propia Class.

Piensa mejor en las alternativas que realmente existen para ahorrarte tiempo, antes de volver a hacer algo cómo lo que has hecho :P.

yo por ejemplo no me puse a escribir una a una la enumeración con las +120 entradas, no, esa enumeración la conseguí desarrollando un código de 2 o 3 lineas para reemplazar el orden de las palabras (los números a la derecha) de la lista original, y luego cojí un editor de texto que soportase expresiones regulares (Sublime Text) y usé el reemplazo mediante dichas expresiones para los caracteres ilegales; En caso de no haber tenido un editor que lo hiciese, habría desarrollado un pequeño código de pocas lineas para utilizar RegEx con los mismos fines.

Ejemplo:
Código (vbnet) [Seleccionar]
Public Class Form1

   Dim licenses As String =
       <a>
0 Invalid License Code
1 Nintendo
5 Zamuse
8 Capcom
9 HOT B
10 Jaleco
11 STORM (Sales Curve) (1)
15 Mebio Software
18 Gremlin Graphics
21 COBRA Team
22 Human/Field
24 Hudson Soft
26 Yanoman
28 Tecmo (1)
30 Forum
31 Park Place Productions / VIRGIN
33 Tokai Engeneering (SUNSOFT?)
34 POW
35 Loriciel / Micro World
38 Enix
40 Kemco (1)
41 Seta Co.,Ltd.
45 Visit Co.,Ltd.
53 HECT
61 Loriciel
64 Seika Corp.
65 UBI Soft
71 Spectrum Holobyte
73 Irem
75 Raya Systems/Sculptured Software
76 Renovation Pruducts
77 Malibu Games (T*HQ Inc.) / Black Pearl
79 U.S. Gold
80 Absolute Entertainment
81 Acclaim
82 Activision
83 American Sammy
84 GameTek
85 Hi Tech
86 LJN Toys
90 Mindscape
93 Technos Japan Corp. (Tradewest)
95 American Softworks Corp.
96 Titus
97 Virgin Games
98 Maxis
103 Ocean
105 Electronic Arts
107 Laser Beam
110 Elite
111 Electro Brain
112 Infogrames
113 Interplay
114 LucasArts
115 Sculptured Soft
117 STORM (Sales Curve) (2)
120 THQ Software
121 Accolade Inc.
122 Triffix Entertainment
124 Microprose
127 Kemco (2)
130 Namcot/Namco Ltd. (1)
132 Koei/Koei! (second license?)
134 Tokuma Shoten Intermedia
136 DATAM-Polystar
139 Bullet-Proof Software
140 Vic Tokai
143 I'Max
145 CHUN Soft
146 Video System Co., Ltd.
147 BEC
151 Kaneco
153 Pack in Video
154 Nichibutsu
155 TECMO (2)
156 Imagineer Co.
160 Wolf Team
164 Konami
165 K.Amusement
167 Takara
169 Technos Jap. ????
170 JVC
172 Toei Animation
173 Toho
175 Namcot/Namco Ltd. (2)
177 ASCII Co. Activison
178 BanDai America
180 Enix
182 Halken
186 Culture Brain
187 Sunsoft
188 Toshiba EMI/System Vision
189 Sony (Japan) / Imagesoft
191 Sammy
192 Taito
194 Kemco (3) ????
195 Square
196 NHK
197 Data East
198 Tonkin House
200 KOEI
202 Konami USA
205 Meldac/KAZe
206 PONY CANYON
207 Sotsu Agency
209 Sofel
210 Quest Corp.
211 Sigma
214 Naxat
216 Capcom Co., Ltd. (2)
217 Banpresto
219 Hiro
221 NCS
222 Human Entertainment
223 Ringler Studios
224 K.K. DCE / Jaleco
226 Sotsu Agency
228 TandESoft;
229 EPOCH Co.,Ltd.
231 Athena
232 Asmik
233 Natsume
234 King/A Wave
235 Atlus
236 Sony Music
238 Psygnosis / igs
243 Beam Software
244 Tec Magik
255 Hudson Soft
</a>.Value

   Private licDict As New Dictionary(Of String, String)

   Private Sub CreateLicenseDictionary()

       For Each line As String In licenses.Trim.Split({ControlChars.Lf}, StringSplitOptions.RemoveEmptyEntries)

           Dim code As Byte = Convert.ToByte(line.Substring(0, line.IndexOf(" "c)))
           Dim codeHex As String = Convert.ToString(code, toBase:=16)
           Dim name As String = line.Substring(line.IndexOf(" "c), line.Length - code.ToString.Length)

           licDict.Add(codeHex, name)

       Next line

   End Sub

   Private Sub Test()

       textBox_Codigo_Licencia_2.Text = Me.licDict(Codigo_Licencia)

   End Sub

End Class


Puedes hacer algo parecido en C#, con los datos de la variable "code" y "name" también puedes crear la enumeración de C# en un archivo de texto, construyendo el string con ese formato específico, que solo tendrías que copiar y pegar en tu código fuente.

En fin... será por porisiblidades.

Saludos!