Partir archivo

Iniciado por Meta, 10 Agosto 2014, 04:27 AM

0 Miembros y 1 Visitante están viendo este tema.

Meta

Hola:

Uso Visual Express 2013. Tengo un archivo binario llamado Archivo.dat que pesa 2 MB. Quiero hacer un programa que sea capaz de partirlo en 2 partes a 1 MB cada uno o lo que yo quiera como hacer Winrar. Después unirlo. El proceso es el siguiente.

    Cargar tu aplicación un archivo llamado Archivo.dat que es binario, puede ser cualquiera, como un archivo.jpg.
    Al cargar el Archivo.dat detecta cuantos MB son, por ejemplo 2 MB.
    Opción para elegir cuantos KB a partir, en este caso, la mitad.
    Se renombra los archivos llamado Archivo_01.bin y Archivo_02.bin de 1 MB cada uno.
    Fin de programa.

¿Cómo se hace?

Espero que no sea muy complicado hacer estas cosas.

Saludo.
Tutoriales Electrónica y PIC: http://electronica-pic.blogspot.com/

engel lex

basicamente lo que tienes que hacer es leer el archivo en modo binario, crear un archivo binario vacío, leer del original y guardar la sección que te interese...


aqui un ejemplo en ingles http://socketprogramming.blogspot.com/2008/11/split-and-assemble-large-file-around.html

y la informacion de lectura/escritura en msdn http://msdn.microsoft.com/es-es/library/aa711083(v=vs.71).aspx
El problema con la sociedad actualmente radica en que todos creen que tienen el derecho de tener una opinión, y que esa opinión sea validada por todos, cuando lo correcto es que todos tengan derecho a una opinión, siempre y cuando esa opinión pueda ser ignorada, cuestionada, e incluso ser sujeta a burla, particularmente cuando no tiene sentido alguno.

Meta

Cita de: engel lex en 10 Agosto 2014, 04:36 AM
basicamente lo que tienes que hacer es leer el archivo en modo binario, crear un archivo binario vacío, leer del original y guardar la sección que te interese...


aqui un ejemplo en ingles http://socketprogramming.blogspot.com/2008/11/split-and-assemble-large-file-around.html

y la informacion de lectura/escritura en msdn http://msdn.microsoft.com/es-es/library/aa711083(v=vs.71).aspx

Gracias, voy a analizaro.
Tutoriales Electrónica y PIC: http://electronica-pic.blogspot.com/

Eleкtro

#3
Cita de: Meta en 10 Agosto 2014, 04:27 AM¿Cómo se hace?

¿Que has intentado?, ¿donde está tu código?, aquí no hacemos el trabajo a nadie, ayudamos a que lo puedas hacer por ti mismo.

Tienes todo tipo de ejemplos en Google: http://www.codeproject.com/Articles/2737/File-Split-Merge-Tool

De todas formas, la idea me pareció interesante, aquí va mi enfoque:

Cita de: http://foro.elhacker.net/net/libreria_de_snippets_compartan_aqui_sus_snippets-t378770.0.html;msg1959642#msg1959642
Código (vbnet) [Seleccionar]
   ' Split File
   ' By Elektro
   '
   ' Example Usage:
   ' SplitFile(InputFile:="C:\Test.mp3", ChunkSize:=(1024L ^ 2L), ChunkName:="Test.Part", ChunkExt:="mp3", Overwrite:=True)

   ''' <summary>
   ''' Splits a file into chunks.
   ''' </summary>
   ''' <param name="InputFile">
   ''' Indicates the input file to split.
   ''' </param>
   ''' <param name="ChunkSize">
   ''' Indicates the size of each chunk.
   ''' </param>
   ''' <param name="ChunkName">
   ''' Indicates the chunk filename format.
   ''' Default format is: 'FileName.ChunkIndex.FileExt'
   ''' </param>
   ''' <param name="ChunkExt">
   ''' Indicates the chunk file-extension.
   ''' If this value is <c>Null</c>, the input file-extension will be used.
   ''' </param>
   ''' <param name="Overwrite">
   ''' If set to <c>true</c>, chunk files will replace any existing file;
   ''' Otherwise, an exception will be thrown.
   ''' </param>
   ''' <exception cref="System.OverflowException">'ChunkSize' should be smaller than the Filesize.</exception>
   ''' <exception cref="System.IO.IOException"></exception>
   Public Sub SplitFile(ByVal InputFile As String,
                        ByVal ChunkSize As Long,
                        Optional ByVal ChunkName As String = Nothing,
                        Optional ByVal ChunkExt As String = Nothing,
                        Optional ByVal Overwrite As Boolean = False)

       ' FileInfo instance of the input file.
       Dim fInfo As New IO.FileInfo(InputFile)

       ' The buffer to read data and write the chunks.
       Dim Buffer As Byte() = New Byte() {}

       ' The buffer length.
       Dim BufferSize As Integer = 1048576 ' 1048576 = 1 mb | 33554432 = 32 mb | 67108864 = 64 mb

       ' Counts the length of the current chunk file.
       Dim BytesWritten As Long = 0L

       ' The total amount of chunks to create.
       Dim ChunkCount As Integer = CInt(Math.Floor(fInfo.Length / ChunkSize))

       ' Keeps track of the current chunk.
       Dim ChunkIndex As Integer = 0I

       ' A zero-filled string to enumerate the chunk files.
       Dim Zeros As String = String.Empty

       ' The given filename for each chunk.
       Dim ChunkFile As String = String.Empty

       ' The chunk file basename.
       ChunkName = If(String.IsNullOrEmpty(ChunkName),
                      IO.Path.Combine(fInfo.DirectoryName, IO.Path.GetFileNameWithoutExtension(fInfo.Name)),
                      IO.Path.Combine(fInfo.DirectoryName, ChunkName))

       ' The chunk file extension.
       ChunkExt = If(String.IsNullOrEmpty(ChunkExt),
                     fInfo.Extension.Substring(1I),
                     ChunkExt)

       ' If ChunkSize is bigger than filesize then...
       If ChunkSize >= fInfo.Length Then
           Throw New OverflowException("'ChunkSize' should be smaller than the Filesize.")
           Exit Sub

           ' For cases where a chunksize is smaller than the buffersize.
       ElseIf ChunkSize < BufferSize Then
           BufferSize = CInt(ChunkSize)

       End If ' ChunkSize <>...

       ' If not file-overwrite is allowed then...
       If Not Overwrite Then

           For Index As Integer = 0I To (ChunkCount)

               ' Set chunk filename.
               Zeros = New String("0", CStr(ChunkCount).Length - CStr(Index + 1I).Length)
               ChunkFile = String.Format("{0}.{1}.{2}", ChunkName, Zeros & CStr(Index + 1I), ChunkExt)

               ' If chunk file already exists then...
               If IO.File.Exists(ChunkFile) Then

                   Throw New IO.IOException(String.Format("File already exist: {0}", ChunkFile))
                   Exit Sub

               End If ' IO.File.Exists(ChunkFile)

           Next Index

           Zeros = String.Empty
           ChunkFile = String.Empty

       End If ' Overwrite

       ' Open the file to start reading bytes.
       Using InputStream As New IO.FileStream(fInfo.FullName, IO.FileMode.Open)

           Using BinaryReader As New IO.BinaryReader(InputStream)

               While (InputStream.Position < InputStream.Length)

                   ' Set chunk filename.
                   Zeros = New String("0", CStr(ChunkCount).Length - CStr(ChunkIndex + 1I).Length)
                   ChunkFile = String.Format("{0}.{1}.{2}", ChunkName, Zeros & CStr(ChunkIndex + 1I), ChunkExt)

                   ' Reset written byte-length counter.
                   BytesWritten = 0L

                   ' Create the chunk file to Write the bytes.
                   Using OutputStream As New IO.FileStream(ChunkFile, IO.FileMode.Create)

                       Using BinaryWriter As New IO.BinaryWriter(OutputStream)

                           ' Read until reached the end-bytes of the input file.
                           While (BytesWritten < ChunkSize) AndAlso (InputStream.Position < InputStream.Length)

                               ' Read bytes from the original file (BufferSize byte-length).
                               Buffer = BinaryReader.ReadBytes(BufferSize)

                               ' Write those bytes in the chunk file.
                               BinaryWriter.Write(Buffer)

                               ' Increment the size counter.
                               BytesWritten += Buffer.Count

                           End While ' (BytesWritten < ChunkSize) AndAlso (InputStream.Position < InputStream.Length)

                           OutputStream.Flush()

                       End Using ' BinaryWriter

                   End Using ' OutputStream

                   ChunkIndex += 1I 'Increment file counter

               End While ' InputStream.Position < InputStream.Length

           End Using ' BinaryReader

       End Using ' InputStream

   End Sub

Saludos.








Meta

Buenas:

Los ejemplos que he hecho es cortar una cadena de unas variables en C#, no en archivo. Lo que he hecho era modificar binarios, ahora me toca cortarlos.

Código (csharp) [Seleccionar]

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.IO; // No olvidar este using.

namespace Archivo_Binario
{
  class Program
  {
    static void Main(string[] args)
    {
      Console.Title = "Moficicar cabeceras";


      while (true)
      {
        Console.WriteLine(@"Seleccione C, c, M, m, R, r, L, l, S o s.
C o c = Limpiar pantalla.
M o m = Modificar.
R o r = Recuperar.
L o l = Leer.
S o s = Salir.
");
        string str = Console.ReadLine();

        switch (str)
        {
            case "C": // Limpiar pantalla.
            case "c":
                Console.Clear();
                break;

            case "M": // Modificar.
            case "m":
                Modificar();
                break;

            case "R": // Recuperar.
            case "r":
                Recuperar();
                break;

            case "L": // Leer.
            case "l":
                Leer();
                break;

            case "S": // Salir.
            case "s":
                // Espera por una tecla para terminar la aplicación.
                Environment.Exit(0);
                break;

            default:
            Console.WriteLine("Selección inválida. Por favor, selecciona M, m, R, r, S o l.");
            break;
        }

        if (str.ToUpper() == "S")
        {
          break;
        }

        //Console.ReadLine();
      }
    }

    private static void Modificar()
    {
      try
      {
        FileStream fs = new FileStream(@"C:\Archivo.zip", FileMode.Open, FileAccess.ReadWrite);
        BinaryReader br = new BinaryReader(fs);
        BinaryWriter bw = new BinaryWriter(fs);

        //if ((br.ReadByte() == 'P') && (br.ReadByte() == 'K'))
        //{
          fs.Position = 0;
          bw.Write((byte)0x4D);
          bw.Write((byte)0x53);

          fs.Position = 0x25;
          bw.Write((byte)0xA9); // ©.
          bw.Write((byte)0x4D); // M.
          bw.Write((byte)0x53); // S.

          fs.Position = 0xC53A40;
          bw.Write((byte)0x00);
          bw.Write((byte)0x00);
          bw.Write((byte)0x00);
          bw.Write((byte)0x00);
          bw.Write((byte)0x00);
          bw.Write((byte)0x00);
          bw.Write((byte)0x00);
          bw.Write((byte)0x00);
          bw.Write((byte)0x00);
          bw.Write((byte)0x00);
          bw.Write((byte)0x00);
          bw.Write((byte)0x00);
          bw.Write((byte)0x00);
          bw.Write((byte)0x00);
          bw.Write((byte)0x00);
          bw.Write((byte)0x00);
        //}

        //
        br.Close();
        bw.Close();
        Console.WriteLine("Se ha modificado correctamente.");
      }
      catch
      {
        Console.WriteLine("Error. No encuentra el archivo.");
      }
    }

    private static void Recuperar()
    {
      try
      {
        FileStream fs = new FileStream(@"C:\Archivo.zip", FileMode.Open, FileAccess.ReadWrite);
        BinaryReader br = new BinaryReader(fs);
        BinaryWriter bw = new BinaryWriter(fs);

        //if ((br.ReadByte() == 'M') && (br.ReadByte() == 'S'))
        //{
          fs.Position = 0;
          bw.Write((byte)'P');
          bw.Write((byte)'K');

          fs.Position = 0x25;
          bw.Write((byte)0x2F); // /.
          bw.Write((byte)0x50); // P.
          bw.Write((byte)0x4B); // K.
        //}
          fs.Position = 0xC53A40;
          bw.Write((byte)0xBF);
          bw.Write((byte)0xCE);
          bw.Write((byte)0x01);
          bw.Write((byte)0xA0);
          bw.Write((byte)0x9F);
          bw.Write((byte)0x17);
          bw.Write((byte)0xDB);
          bw.Write((byte)0x5D);
          bw.Write((byte)0xBF);
          bw.Write((byte)0xCE);
          bw.Write((byte)0x01);
          bw.Write((byte)0x50);
          bw.Write((byte)0x4B);
          bw.Write((byte)0x05);
          bw.Write((byte)0x06);
          bw.Write((byte)0x00);
        //
        br.Close();
        bw.Close();
        Console.WriteLine("Se ha recuperado correctamente.");
      }
      catch
      {
        Console.WriteLine("Error. No encuentra el archivo.");
      }
    }

    private static void Leer()
    {
        FileStream fs = new FileStream(@"C:\Archivo.zip", FileMode.Open);
        BinaryReader br = new BinaryReader(fs);

        string Valores = null;
        for (int i = 0x181760; i <= 0x181795; i++)
        {
            br.BaseStream.Position = i;
            Valores += br.ReadByte().ToString("X2");
        }

        Console.WriteLine(Valores);
        Valores = null;

        string misBytes = @"57 69 6E 6E 74 6E 74 2F 56 79 4B 67 7A 2E 6A 70 67 0A 00 20 00 00 00 00 00 01 00 18 00 00 A0 19 28 04 1F CC 01 0A 07 17 DB 5D BF CE 01 0A 07 17 DB 5D BF CE 01 50 4B 01 02 1F 00 14 00 00 00 08 00 7D 47 A2 3E 94 19 72 D9 31 B9 01 00 4E B9 01 00 19 00 24 00 00 00 00 00 00 00 20 00 00 00 1E FD C0 00 57 69 6E 6E 74 6E 74 2F 57 69 6E 6E 74 6E 74 2F 57 65 4B 48 33 2E 6A 70 67 0A 00 20 00 00 00 00 00 01 00 18 00 00 93 22 EE 9E 08 CC 01 55 53 17 DB 5D BF CE 01 55 53 17 DB 5D BF CE 01 50 4B 01 02 1F 00 14 00 00 00 08 00 2C 4D A3 3E F7 60 2F 06 EA 74 02 00 16 75 02 00 19 00 24 00 00 00 00 00 00 00 20 00 00 00 86 B6 C2 00 57 69 6E 6E 74 6E 74 2F 57 69 6E 6E 74 6E 74 2F 58 49 30 67 50 2E 6A 70 67 0A 00 20 00 00 00 00 00 01 00 18 00 00 D2 51 E2 6D 09 CC 01 A0 9F 17 DB 5D BF CE 01 A0 9F 17 DB 5D BF CE 01 50 4B 05 06 00 00 00 00 22 00 22 00 A4 0E 00 00 A7 2B C5 00 00";

        string[] listaDeBytes = misBytes.Split(' ');
        foreach (string hex in listaDeBytes)
        {
            //Aquí la variable hex vale, por ejemplo "6E".
            //Conviértela a binario y usa el resultado en bw.Write(...)
           
                misBytes = Convert.ToString(Convert.ToInt32(hex, 16), 2);
                Console.WriteLine(hex);
        }
            br.Close();
    }
  }
}



Gracias por la ayuda. Aunque no tenga nada que ver este código, irá relacionado con cortar.
Tutoriales Electrónica y PIC: http://electronica-pic.blogspot.com/