elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Introducción a Git (Primera Parte)


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  .NET (C#, VB.NET, ASP) (Moderador: kub0x)
| | | |-+  Partir archivo
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: Partir archivo  (Leído 3,397 veces)
Meta


Desconectado Desconectado

Mensajes: 3.438



Ver Perfil WWW
Partir archivo
« en: 10 Agosto 2014, 04:27 am »

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.


En línea

engel lex
Moderador Global
***
Desconectado Desconectado

Mensajes: 15.514



Ver Perfil
Re: Partir archivo
« Respuesta #1 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


En línea

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


Desconectado Desconectado

Mensajes: 3.438



Ver Perfil WWW
Re: Partir archivo
« Respuesta #2 en: 10 Agosto 2014, 08:32 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.
En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
Re: Partir archivo
« Respuesta #3 en: 10 Agosto 2014, 13:36 pm »

¿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:

Código
  1.    ' Split File
  2.    ' By Elektro
  3.    '
  4.    ' Example Usage:
  5.    ' SplitFile(InputFile:="C:\Test.mp3", ChunkSize:=(1024L ^ 2L), ChunkName:="Test.Part", ChunkExt:="mp3", Overwrite:=True)
  6.  
  7.    ''' <summary>
  8.    ''' Splits a file into chunks.
  9.    ''' </summary>
  10.    ''' <param name="InputFile">
  11.    ''' Indicates the input file to split.
  12.    ''' </param>
  13.    ''' <param name="ChunkSize">
  14.    ''' Indicates the size of each chunk.
  15.    ''' </param>
  16.    ''' <param name="ChunkName">
  17.    ''' Indicates the chunk filename format.
  18.    ''' Default format is: 'FileName.ChunkIndex.FileExt'
  19.    ''' </param>
  20.    ''' <param name="ChunkExt">
  21.    ''' Indicates the chunk file-extension.
  22.    ''' If this value is <c>Null</c>, the input file-extension will be used.
  23.    ''' </param>
  24.    ''' <param name="Overwrite">
  25.    ''' If set to <c>true</c>, chunk files will replace any existing file;
  26.    ''' Otherwise, an exception will be thrown.
  27.    ''' </param>
  28.    ''' <exception cref="System.OverflowException">'ChunkSize' should be smaller than the Filesize.</exception>
  29.    ''' <exception cref="System.IO.IOException"></exception>
  30.    Public Sub SplitFile(ByVal InputFile As String,
  31.                         ByVal ChunkSize As Long,
  32.                         Optional ByVal ChunkName As String = Nothing,
  33.                         Optional ByVal ChunkExt As String = Nothing,
  34.                         Optional ByVal Overwrite As Boolean = False)
  35.  
  36.        ' FileInfo instance of the input file.
  37.        Dim fInfo As New IO.FileInfo(InputFile)
  38.  
  39.        ' The buffer to read data and write the chunks.
  40.        Dim Buffer As Byte() = New Byte() {}
  41.  
  42.        ' The buffer length.
  43.        Dim BufferSize As Integer = 1048576 ' 1048576 = 1 mb | 33554432 = 32 mb | 67108864 = 64 mb
  44.  
  45.        ' Counts the length of the current chunk file.
  46.        Dim BytesWritten As Long = 0L
  47.  
  48.        ' The total amount of chunks to create.
  49.        Dim ChunkCount As Integer = CInt(Math.Floor(fInfo.Length / ChunkSize))
  50.  
  51.        ' Keeps track of the current chunk.
  52.        Dim ChunkIndex As Integer = 0I
  53.  
  54.        ' A zero-filled string to enumerate the chunk files.
  55.        Dim Zeros As String = String.Empty
  56.  
  57.        ' The given filename for each chunk.
  58.        Dim ChunkFile As String = String.Empty
  59.  
  60.        ' The chunk file basename.
  61.        ChunkName = If(String.IsNullOrEmpty(ChunkName),
  62.                       IO.Path.Combine(fInfo.DirectoryName, IO.Path.GetFileNameWithoutExtension(fInfo.Name)),
  63.                       IO.Path.Combine(fInfo.DirectoryName, ChunkName))
  64.  
  65.        ' The chunk file extension.
  66.        ChunkExt = If(String.IsNullOrEmpty(ChunkExt),
  67.                      fInfo.Extension.Substring(1I),
  68.                      ChunkExt)
  69.  
  70.        ' If ChunkSize is bigger than filesize then...
  71.        If ChunkSize >= fInfo.Length Then
  72.            Throw New OverflowException("'ChunkSize' should be smaller than the Filesize.")
  73.            Exit Sub
  74.  
  75.            ' For cases where a chunksize is smaller than the buffersize.
  76.        ElseIf ChunkSize < BufferSize Then
  77.            BufferSize = CInt(ChunkSize)
  78.  
  79.        End If ' ChunkSize <>...
  80.  
  81.        ' If not file-overwrite is allowed then...
  82.        If Not Overwrite Then
  83.  
  84.            For Index As Integer = 0I To (ChunkCount)
  85.  
  86.                ' Set chunk filename.
  87.                Zeros = New String("0", CStr(ChunkCount).Length - CStr(Index + 1I).Length)
  88.                ChunkFile = String.Format("{0}.{1}.{2}", ChunkName, Zeros & CStr(Index + 1I), ChunkExt)
  89.  
  90.                ' If chunk file already exists then...
  91.                If IO.File.Exists(ChunkFile) Then
  92.  
  93.                    Throw New IO.IOException(String.Format("File already exist: {0}", ChunkFile))
  94.                    Exit Sub
  95.  
  96.                End If ' IO.File.Exists(ChunkFile)
  97.  
  98.            Next Index
  99.  
  100.            Zeros = String.Empty
  101.            ChunkFile = String.Empty
  102.  
  103.        End If ' Overwrite
  104.  
  105.        ' Open the file to start reading bytes.
  106.        Using InputStream As New IO.FileStream(fInfo.FullName, IO.FileMode.Open)
  107.  
  108.            Using BinaryReader As New IO.BinaryReader(InputStream)
  109.  
  110.                While (InputStream.Position < InputStream.Length)
  111.  
  112.                    ' Set chunk filename.
  113.                    Zeros = New String("0", CStr(ChunkCount).Length - CStr(ChunkIndex + 1I).Length)
  114.                    ChunkFile = String.Format("{0}.{1}.{2}", ChunkName, Zeros & CStr(ChunkIndex + 1I), ChunkExt)
  115.  
  116.                    ' Reset written byte-length counter.
  117.                    BytesWritten = 0L
  118.  
  119.                    ' Create the chunk file to Write the bytes.
  120.                    Using OutputStream As New IO.FileStream(ChunkFile, IO.FileMode.Create)
  121.  
  122.                        Using BinaryWriter As New IO.BinaryWriter(OutputStream)
  123.  
  124.                            ' Read until reached the end-bytes of the input file.
  125.                            While (BytesWritten < ChunkSize) AndAlso (InputStream.Position < InputStream.Length)
  126.  
  127.                                ' Read bytes from the original file (BufferSize byte-length).
  128.                                Buffer = BinaryReader.ReadBytes(BufferSize)
  129.  
  130.                                ' Write those bytes in the chunk file.
  131.                                BinaryWriter.Write(Buffer)
  132.  
  133.                                ' Increment the size counter.
  134.                                BytesWritten += Buffer.Count
  135.  
  136.                            End While ' (BytesWritten < ChunkSize) AndAlso (InputStream.Position < InputStream.Length)
  137.  
  138.                            OutputStream.Flush()
  139.  
  140.                        End Using ' BinaryWriter
  141.  
  142.                    End Using ' OutputStream
  143.  
  144.                    ChunkIndex += 1I 'Increment file counter
  145.  
  146.                End While ' InputStream.Position < InputStream.Length
  147.  
  148.            End Using ' BinaryReader
  149.  
  150.        End Using ' InputStream
  151.  
  152.    End Sub

Saludos.
« Última modificación: 10 Agosto 2014, 13:41 pm por Eleкtro » En línea

Meta


Desconectado Desconectado

Mensajes: 3.438



Ver Perfil WWW
Re: Partir archivo
« Respuesta #4 en: 11 Agosto 2014, 00:05 am »

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
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6.  
  7. using System.IO; // No olvidar este using.
  8.  
  9. namespace Archivo_Binario
  10. {
  11.  class Program
  12.  {
  13.    static void Main(string[] args)
  14.    {
  15.      Console.Title = "Moficicar cabeceras";
  16.  
  17.  
  18.      while (true)
  19.      {
  20.        Console.WriteLine(@"Seleccione C, c, M, m, R, r, L, l, S o s.
  21. C o c = Limpiar pantalla.
  22. M o m = Modificar.
  23. R o r = Recuperar.
  24. L o l = Leer.
  25. S o s = Salir.
  26. ");
  27.        string str = Console.ReadLine();
  28.  
  29.        switch (str)
  30.        {
  31.            case "C": // Limpiar pantalla.
  32.            case "c":
  33.                Console.Clear();
  34.                break;
  35.  
  36.            case "M": // Modificar.
  37.            case "m":
  38.                Modificar();
  39.                break;
  40.  
  41.            case "R": // Recuperar.
  42.            case "r":
  43.                Recuperar();
  44.                break;
  45.  
  46.            case "L": // Leer.
  47.            case "l":
  48.                Leer();
  49.                break;
  50.  
  51.            case "S": // Salir.
  52.            case "s":
  53.                // Espera por una tecla para terminar la aplicación.
  54.                Environment.Exit(0);
  55.                break;
  56.  
  57.            default:
  58.            Console.WriteLine("Selección inválida. Por favor, selecciona M, m, R, r, S o l.");
  59.            break;
  60.        }
  61.  
  62.        if (str.ToUpper() == "S")
  63.        {
  64.          break;
  65.        }
  66.  
  67.        //Console.ReadLine();
  68.      }
  69.    }
  70.  
  71.    private static void Modificar()
  72.    {
  73.      try
  74.      {
  75.        FileStream fs = new FileStream(@"C:\Archivo.zip", FileMode.Open, FileAccess.ReadWrite);
  76.        BinaryReader br = new BinaryReader(fs);
  77.        BinaryWriter bw = new BinaryWriter(fs);
  78.  
  79.        //if ((br.ReadByte() == 'P') && (br.ReadByte() == 'K'))
  80.        //{
  81.          fs.Position = 0;
  82.          bw.Write((byte)0x4D);
  83.          bw.Write((byte)0x53);
  84.  
  85.          fs.Position = 0x25;
  86.          bw.Write((byte)0xA9); // ©.
  87.          bw.Write((byte)0x4D); // M.
  88.          bw.Write((byte)0x53); // S.
  89.  
  90.          fs.Position = 0xC53A40;
  91.          bw.Write((byte)0x00);
  92.          bw.Write((byte)0x00);
  93.          bw.Write((byte)0x00);
  94.          bw.Write((byte)0x00);
  95.          bw.Write((byte)0x00);
  96.          bw.Write((byte)0x00);
  97.          bw.Write((byte)0x00);
  98.          bw.Write((byte)0x00);
  99.          bw.Write((byte)0x00);
  100.          bw.Write((byte)0x00);
  101.          bw.Write((byte)0x00);
  102.          bw.Write((byte)0x00);
  103.          bw.Write((byte)0x00);
  104.          bw.Write((byte)0x00);
  105.          bw.Write((byte)0x00);
  106.          bw.Write((byte)0x00);
  107.        //}
  108.  
  109.        //
  110.        br.Close();
  111.        bw.Close();
  112.        Console.WriteLine("Se ha modificado correctamente.");
  113.      }
  114.      catch
  115.      {
  116.        Console.WriteLine("Error. No encuentra el archivo.");
  117.      }
  118.    }
  119.  
  120.    private static void Recuperar()
  121.    {
  122.      try
  123.      {
  124.        FileStream fs = new FileStream(@"C:\Archivo.zip", FileMode.Open, FileAccess.ReadWrite);
  125.        BinaryReader br = new BinaryReader(fs);
  126.        BinaryWriter bw = new BinaryWriter(fs);
  127.  
  128.        //if ((br.ReadByte() == 'M') && (br.ReadByte() == 'S'))
  129.        //{
  130.          fs.Position = 0;
  131.          bw.Write((byte)'P');
  132.          bw.Write((byte)'K');
  133.  
  134.          fs.Position = 0x25;
  135.          bw.Write((byte)0x2F); // /.
  136.          bw.Write((byte)0x50); // P.
  137.          bw.Write((byte)0x4B); // K.
  138.        //}
  139.          fs.Position = 0xC53A40;
  140.          bw.Write((byte)0xBF);
  141.          bw.Write((byte)0xCE);
  142.          bw.Write((byte)0x01);
  143.          bw.Write((byte)0xA0);
  144.          bw.Write((byte)0x9F);
  145.          bw.Write((byte)0x17);
  146.          bw.Write((byte)0xDB);
  147.          bw.Write((byte)0x5D);
  148.          bw.Write((byte)0xBF);
  149.          bw.Write((byte)0xCE);
  150.          bw.Write((byte)0x01);
  151.          bw.Write((byte)0x50);
  152.          bw.Write((byte)0x4B);
  153.          bw.Write((byte)0x05);
  154.          bw.Write((byte)0x06);
  155.          bw.Write((byte)0x00);
  156.        //
  157.        br.Close();
  158.        bw.Close();
  159.        Console.WriteLine("Se ha recuperado correctamente.");
  160.      }
  161.      catch
  162.      {
  163.        Console.WriteLine("Error. No encuentra el archivo.");
  164.      }
  165.    }
  166.  
  167.    private static void Leer()
  168.    {
  169.        FileStream fs = new FileStream(@"C:\Archivo.zip", FileMode.Open);
  170.        BinaryReader br = new BinaryReader(fs);
  171.  
  172.        string Valores = null;
  173.        for (int i = 0x181760; i <= 0x181795; i++)
  174.        {
  175.            br.BaseStream.Position = i;
  176.            Valores += br.ReadByte().ToString("X2");
  177.        }
  178.  
  179.        Console.WriteLine(Valores);
  180.        Valores = null;
  181.  
  182.        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";
  183.  
  184.        string[] listaDeBytes = misBytes.Split(' ');
  185.        foreach (string hex in listaDeBytes)
  186.        {
  187.            //Aquí la variable hex vale, por ejemplo "6E".
  188.            //Conviértela a binario y usa el resultado en bw.Write(...)
  189.  
  190.                misBytes = Convert.ToString(Convert.ToInt32(hex, 16), 2);
  191.                Console.WriteLine(hex);
  192.        }
  193.            br.Close();
  194.    }
  195.  }
  196. }
  197.  
  198.  

Gracias por la ayuda. Aunque no tenga nada que ver este código, irá relacionado con cortar.
En línea

Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
Crear archivo reproducible de DVD a partir de archivo MPG con Canopus ProCoder
Multimedia
aula18 2 5,373 Último mensaje 8 Septiembre 2004, 23:28 pm
por Songoku
Partir un archivo de video
Multimedia
gande876 1 1,415 Último mensaje 29 Noviembre 2006, 00:10 am
por Sourraund
Partir archivo « 1 2 »
.NET (C#, VB.NET, ASP)
Meta 10 6,536 Último mensaje 5 Junio 2015, 00:36 am
por DarK_FirefoX
Partir archivo con C#
.NET (C#, VB.NET, ASP)
Meta 1 2,075 Último mensaje 25 Mayo 2015, 21:27 pm
por Stakewinner00
Creando un tablero a partir de un archivo « 1 2 »
Programación C/C++
Sothu 17 5,879 Último mensaje 13 Enero 2016, 18:29 pm
por MAFUS
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines